dictionary and __getattr__

Skip Montanaro skip at pobox.com
Thu Sep 6 10:36:46 EDT 2001


    > 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:

    % ./python
    Python 2.2a2+ (#23, Sep  5 2001, 21:48:23) 
    [GCC 2.96 20000731 (Linux-Mandrake 8.0 2.96-0.48mdk)] on linux2
    Type "help", "copyright", "credits" or "license" for more information.
    >>> dictionary
    <type 'dictionary'>
    >>> class AttributeDict(dictionary):
    ...   __getattr__ = dictionary.__getitem__
    ... 
    >>> d = AttributeDict()
    >>> d['a'] = 1
    >>> d.a
    1

S




More information about the Python-list mailing list