[Baypiggies] A properties and obj.__dict__ question

Simeon Franklin simeonf at gmail.com
Fri Sep 9 06:29:06 CEST 2011

Sounds like a job for the inspect module. I don't have a great deal of
familiarity here so others may have better suggestions but given a toy

class foo(object):
    def x(self):
        return 1

I can use inspect to get all the attributes and values of objects of class

>>> import inspect
>>> f = foo()
>>>dict(inspect.getmembers(f)) # returns a list of two tuples that I pass to
{'__class__': <class '__main__.foo'>,
 '__delattr__': <method-wrapper '__delattr__' of foo object at 0xa021f4c>,
 '__dict__': {},
... snip ...
 'x': 1}

You could use this dict in your format strings if you know that all
properties are side-effect free. Alternatively if you need a more
sophisticated method you could copy the __dict__ of your object and then add
to it by calling inspect.classify_class_attrs on your class (not the
instance) and noting that properties are identified in the resulting list of
attribute objects. You could then call each one and add its name and value
to your copy of obj.__dict__.

Hmm - this still has you calling all the properties beforehand and seems
clunky. Aha! Try adding a __getitem__ method to your class like:

class foo(object):
    def x(self):
        return 1

    def __getitem__(self, key):
        return getattr(self, key)

And then your class emulates dictionary access (for item retrieval at least)
so that

>>> f = foo()
>>> f['x'] # dict access
>>> "%(x)s" % f # and string formatting with named labels as a consequence

Simeon Franklin
209 846-2151
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/baypiggies/attachments/20110908/1b77a131/attachment.html>

More information about the Baypiggies mailing list