dictionary and __getattr__

Peter Hansen peter at engcorp.com
Thu Sep 6 12:24:09 EDT 2001


Skip Montanaro wrote:
> 
>     > Wouldn't it be nice if this would work:
>     >   d = {'x': 1}
>     >   print d.x
>     > i.e. every entry in a dictionary is also an attribute of the
>     > dictionary itself.
> 
>     Chris> Hey, won't the new 2.2 support for extending built-in classes
>     Chris> such as dictionaries make this both easy and complete?
> 
> Yup:
> 
>     >>> class AttributeDict(dictionary):
>     ...   __getattr__ = dictionary.__getitem__
>     ...
>     >>> d = AttributeDict()
>     >>> d['a'] = 1
>     >>> d.a
>     1

Great, so now instead of KeyError you can get either KeyError
_or_ AttributeError for what is effectively the same problem?

-- 
----------------------
Peter Hansen, P.Eng.
peter at engcorp.com



More information about the Python-list mailing list