Getting a dictionary from an object
Steven Bethard
steven.bethard at gmail.com
Mon Jul 25 22:21:08 EDT 2005
Thanos Tsouanas wrote:
> On Sun, Jul 24, 2005 at 02:14:15PM -0600, Steven Bethard wrote:
>
>>How about something like:
>> dict((name, getattr(obj, name)) for name in dir(obj))
>
> Pretty!!!
>
>>Looks like this will get instance attributes, class attributes and
>>properties just fine.
>
> But not SQLObject's objects...
> Any idea why? (Getting attribute errors, it seems that these
> "attributoids" are not listed in dir(obj), so i have to use my ugly
> dictobj class.. :(
I don't know how SQLObjects are implemented, but I'm guessing they use
__getattr__ or __getattribute__:
py> class C(object):
... w = 1
... @property
... def x(self):
... return 2
... def __init__(self):
... self.y = 3
... def __getattr__(self, name):
... if name == 'z':
... return 4
...
py> c = C()
py> d = dict((name, getattr(c, name)) for name in dir(c))
py> d['w'], d['x'], d['y']
(1, 2, 3)
py> d['z']
Traceback (most recent call last):
File "<interactive input>", line 1, in ?
KeyError: 'z'
Any attribute simulated through __getattr__ or __getattribute__ cannot
be found by dir():
py> dir(c)
['__class__', '__delattr__', '__dict__', '__doc__', '__getattr__',
'__getattribute__', '__hash__', '__init__', '__module__', '__new__',
'__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__str__',
'__weakref__', 'w', 'x', 'y']
For this reason, I try to avoid implementing attributes through these
methods, but sometimes it's unavoidable.
STeVe
More information about the Python-list
mailing list