customized instance dictionaries, anyone?

wolfgang.lipp at gmail.com wolfgang.lipp at gmail.com
Tue Jan 24 12:30:00 EST 2006


some time after posting my `Linkdict recipe`__ to aspn__
-- basically, a dictionary with run-time delegational
lookup, but this is not important here -- i thought gee
that would be fun to make such a customized dictionary
thingie an instance dictionary, and get some custom
namespace behavior out of that.

..  __: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/465748
..  __: http://aspn.activestate.com/

here is a simplified example: first, the customized
dictionary class and a test::


    class CustomDict( dict ):

        defaultValue = 'THIS ITEM NOT AVAILABLE'

        def __getitem__( self, name ):
            try:
                return super( CustomDict, self ).__getitem__( name )
            except KeyError:
                return self.defaultValue

        def __contains__( self, name ):
            return True

        def has_key( self, name ):
            return True

    print '----------------------------------------'
    cd = CustomDict( foo = 'bar' )
    print cd[ 'foo' ]
    print cd[ 'bar' ]
    print 'bar' in cd
    print cd.has_key( 'bar' )

this gives us::

    ----------------------------------------
    bar
    THIS ITEM NOT AVAILABLE
    True
    True

so it appears to work. note that we may have failed to
implement all the conceivable ways to test for
membership (such as searching through ``keys()``) or to
retrieve a value for a given key. more on that below.
now for the class to utilize this definition::

    class X( object ):

        def __init__( self ):
            self.__dict__ = CustomDict( foo = 'bar' )

and the test code for that::

    print '----------------------------------------'
    x = X()
    print x.__dict__[ 'foo' ]
    print x.__dict__[ 'bar' ]
    print x.foo
    print x.bar

which yields::

    ----------------------------------------
    bar
    THIS ITEM NOT AVAILABLE
    bar

    Traceback (most recent call last):
      File "C:\home\projects\__svn__\sundry\#.py", line 39, in ?
        print x.bar
    AttributeError: 'X' object has no attribute 'bar'

ok. so the custom dict *basically* works as expected,
since it does successfully make ``x.foo`` available --
no surprise here. unfortunately, looking up ``x.bar``,
which should really return the default value string,
causes an ``AttributeError`` to be raised.

now of course given the short definition of
``CustomDict``, perhaps there is an essential lookup
method that has not been overwritten but that is
internally used for attribute lookup. however, i
carefully tested my actual class (from the recipe
mentioned above) and also compared the methods defined
there against the standard ``dict()`` interface, and
nothing of importance appeared to be missing. i also
tried to bind the dictionary to the instance earlier, in
``__new__``, to no avail. am i missing something here?

_wolfgang




More information about the Python-list mailing list