Dictionary inheritance

bruno modulix onurb at xiludom.gro
Sat Aug 13 11:30:22 EDT 2005


Talin wrote:
> I want to make a dictionary that acts like a class, in other words,
> supports inheritance: 

I must be missing your point here, since dict is a class and as such
support inheritence:

>>> class MyDict(dict):pass
...
>>> d = MyDict()
>>> d.items()
[]
>>>


> If you attempt to find a key that isn't present,
> it searches a "base" dictionary, which in turn searches its base, and so
> on.

That's not inheritence, that's contextual acquisition (Zope relies
heavily on this concept).

> Now, I realize its fairly trivial to code something like this using
> UserDict, 

If you want to specialize dict, why use UserDict ?

> but given that classes and modules already have this behavior,

Nope. Inheritence is not the solution - unless of course you want to
create a derived class for each and any of your 'nested dict' instances,
which would be a rather strange design...


Here you need composition/delegation:

class HierDict(dict):
    def __init__(self, parent=None):
        self._parent = parent

    def __getitem__(self, name):
        try:
            return super(HierDict,self).__getitem__(name)
        except KeyError, e:
            if self._parent is None:
                raise
            return self._parent[name]

    # to be continued according to your needs


if __name__ == "__main__":
    d = HierDict(None)
    d['test'] = 42
    print d['test']

    d2 = HierDict(d)
    d2['dead'] = "parrot"

    print d2['dead'] # found in d2
    print d2['test'] # found in d


> 
> Also, on a completely different subject: Has there been much discussion
> about extending the use of the 'is' keyword to do type comparisons a la
> C# (e.g. "if x is list:") ?

I don't think there is much to discuss:

x = list
if x is list:
  print "x is list"

Remember that in Python,
1/ type information pertains to objects, not to identifiers
2/ types are objects too

So, the 'is' operator being the identity operator, there is no need to
'extend' it to do type comparisons:

x = []
if type(x) is type([]):
  print "x is a list"

But - even if useful in some special cases -, type comparisons  in
Python are rarely necessary and in most case worst than useless:

def get_foo(a_dict):
  if type(a_dict) is type({}):
    foo = a_dict['foo']
  else:
    raise TypeError, "expected a dict, got something else"

h = HierDict()
h['foo'] = 'bar'

get_foo(h)


...definitively worst than useless...

-
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'onurb at xiludom.gro'.split('@')])"



More information about the Python-list mailing list