Getting a dictionary from an object

Bruno Desthuilliers bdesth.quelquechose at
Sun Jul 24 15:01:40 CEST 2005

Thanos Tsouanas a écrit :
>>On Sat, 23 Jul 2005 11:48:27 +0300, 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

> print foo %do
> where do is a dictobj object...

I gave you a solution based on the Decorator pattern in another post, 
but there is also the possibility to add a __getitem__ method directly 
to the to-be-formatted object's class:

def mygetitem(obj, name):
   return getattr(obj, name)

setattr(obj.__class__, '__getitem__', mygetitem)

BTW, parts of this thread should remind us all that it's usually better 
to clearly describe the *problem* before asking for comments on the 

My 2 cents...

More information about the Python-list mailing list