Getting a dictionary from an object

Thanos Tsouanas thanos at sians.org
Sun Jul 24 08:52:50 EDT 2005


On Sun, Jul 24, 2005 at 03:01:40PM +0200, Bruno Desthuilliers wrote:
> 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)
> obj['bar']

I used what you suggested earlier with the Wrapper, without subclassing
dict anymore.  Thanks!

> <meta>
> 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 
> solution...
> </meta>

"""I would like to have a quick way to create dicts from object, so
that a call to foo['bar'] would return obj.bar."""

Actually this is the problem, (I never said anything about _assigning_
new keys in foo), and the line following it is my question ;)

Thanks again!

-- 
Thanos Tsouanas          .: My Music: http://www.thanostsouanas.com/
http://thanos.sians.org/ .: Sians Music: http://www.sians.org/



More information about the Python-list mailing list