class attrdict

James Stroud jstroud at mbi.ucla.edu
Fri Mar 2 17:10:20 EST 2007


Hallvard B Furuseth wrote:
> Does this class need anything more?
> Is there any risk of a lookup loop?
> Seems to work...
> 
> class attrdict(dict):
>     """Dict where d['foo'] also can be accessed as d.foo"""
>     def __init__(self, *args, **kwargs):
>         self.__dict__ = self
>         dict.__init__(self, *args, **kwargs)
>     def __repr__(self):
>         return dict.__repr__(self).join(("attrdict(", ")"))
> 

Strangely enough, this seems okay since an instance of a dict subclass 
object has an empty __dict__ attribute anyway and so you won't be 
unwittingly destroying some behavior.

James



More information about the Python-list mailing list