Getting a dictionary from an object
Steven D'Aprano
steve at REMOVETHIScyber.com.au
Sun Jul 24 10:02:03 EDT 2005
On Sun, 24 Jul 2005 12:07:02 +0300, Thanos Tsouanas wrote:
> On Sat, Jul 23, 2005 at 06:59:43PM -0600, Steven Bethard wrote:
>> Thanos Tsouanas wrote:
>> > I would like to have a quick way to create dicts from object, so that a
>> > call to foo['bar'] would return obj.bar.
>> >
>> > The following works, but I would prefer to use a built-in way if one
>> > exists. Is there one?
>>
>> 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.
You could have mentioned this earlier.
But I don't think you are correct. As far as I can see, properties do have
an entry in obj.__dict__ the same as other attributes, although there is
certainly some strangeness going on with properties.
Using the sample code from here:
http://www.python.org/2.2.3/descrintro.html#property
class C(object):
def __init__(self):
self.__x = 0
def getx(self):
return self.__x
def setx(self, x):
if x < 0: x = 0
self.__x = x
x = property(getx, setx)
I see _C__x in C().__dict__, exactly as expected. (The _C is Python's
standard name mangling of "semi-private" attributes starting with double
underscores.)
I can't see any way to inspect a Python object and get a list of
properties, so you might have to keep your own list: add a class-attribute
of your object which keeps a list of all the properties:
class Obj:
# various methods, attributes and properties
...
# keep a list of special properties that don't show
# up correctly in __dict__
special = ['foo', 'bar']
# now define a special method that makes a copy of
# __dict__ and adds special properties to it
def objdict(self):
D = self.__dict__.copy()
# assume shallow copy is enough
for property_name in self.special:
D[property_name] = self.__getattribute__(property_name)
return D
then call it when you need it:
print "My object has fields %(foo)s and %(bar)s." % obj.objdict()
It would be nice to see an easier way to introspect objects and get
a list of properties.
--
Steven.
More information about the Python-list
mailing list