Getting a dictionary from an object

Bruno Desthuilliers bdesth.quelquechose at free.quelquepart.fr
Sun Jul 24 18:57:28 CEST 2005


Steven D'Aprano a écrit :
> On Sun, 24 Jul 2005 12:03:47 +0300, Thanos Tsouanas wrote:
>>
>>Please, tell me, how would you print it in my case?
>  
> If I have understood you, you have some object like such:
> 
> obj.foo = 1
> obj.bar = 2
> obj.spam = 'a'
> obj.eggs = 'b'
> 
> say.
> 
> You want to use it something like this:
> 
> print "My object has fields %(foo)s; %(bar)s; %(spam)s; %(eggs)s." % obj
> 
> except that doesn't work. So I would simply change the reference to obj to
> obj.__dict__ and it should do exactly what you want.

Nope, it doesn't work with computed attributes (properties, descriptors, 
...).

The most obvious solution is the decorator pattern - which is somewhat 
the op was trying to do.

Another solution is to dynamically add a __getitem__ method to obj 
before using'em that way, either by setting explicitly the method as an 
attribute of the object's class or by using the import_with_metaclass() 
trick from David Mertz.

(snip)

> It really does help to explain what your functional requirements are,
> instead of focusing on one, possibly pointless, implementation.
> 
+1 on this !-)



More information about the Python-list mailing list