Getting a dictionary from an object

Steven Bethard steven.bethard at gmail.com
Sun Jul 24 16:14:15 EDT 2005


Thanos Tsouanas wrote:
> Steven Bethard wrote:
> 
>>Maybe I'm not understanding your problem, but have you looked at the 
>>builtin "vars()"?
> 
> I didn't know about it, but I knew about object.__dict__ which is, as I
> see equivalent with vars(object).  But it doesn't do the job for me,
> since it fails to grab all obj.foo's, some of them being properties,
> etc.

How about something like:
     dict((name, getattr(obj, name)) for name in dir(obj))

For example:

py> class C(object):
... 	x = 1
... 	@property
... 	def y(self):
... 	    return 2
... 	def __init__(self):
... 	    self.z = 3
...
py> c = C()
py> d = dict((name, getattr(c, name)) for name in dir(c))
py> d['x']
1
py> d['y']
2
py> d['z']
3

Looks like this will get instance attributes, class attributes and 
properties just fine.

STeVe



More information about the Python-list mailing list