Inheriting dictionary

Pavel Panchekha pavpanchekha at gmail.com
Tue Aug 18 16:32:58 EDT 2009


On Aug 18, 4:23 pm, "Jan Kaliszewski" <z... at chopin.edu.pl> wrote:
> 18-08-2009 o 21:44:55 Pavel Panchekha <pavpanche... at gmail.com> wrote:
>
>
>
> > I want a dictionary that will transparently "inherit" from a parent
> > dictionary. So, for example:
>
> > """
> > a = InheritDict({1: "one", 2: "two", 4: "four"})
> > b = InheritDict({3: "three", 4: "foobar"}, inherit_from=a)
>
> > a[1] # "one"
> > a[4] # "four"
> > b[1] # "one"
> > b[3] # "three"
> > b[4] # "foobar"
> > """
>
> > I've written something like this in Python already, but I'm wondering
> > if something like this already exists, preferably written in C, for
> > speed.
>
> AFAIN -- no. But you can easily implement it in Python with rather
> small loss of speed...
>
>   class InheritDict(dict):
>
>       class NoParent(object):
>           def __getitem__(self, key):
>               raise KeyError('There is no %r key in the hierarchy' % key)
>           def __nonzero__(self):
>               return False
>
>       noparent = NoParent()
>
>       def __init__(self, *args, **kwargs):
>           parent = kwargs.pop('inherit_from', self.noparent)
>           dict.__init__(self, *args, **kwargs)
>           self.parent = parent
>
>       def __getitem__(self, key):
>           try:
>               return dict.__getitem__(self, key)
>           except KeyError:
>               return self.parent[key]
>
> Did you do it in similar way? (just curiosity) :-)
>
> Regards,
> *j
>
> --
> Jan Kaliszewski (zuo) <z... at chopin.edu.pl>

I implemented it in a similar way (instead of a try block, an if
block, which works a tiny bit faster; also have a multiple-parents
case, but its rare, and I could do that in Python without much loss of
speed). Pity that there's no C version; this InheritDict is kind of
the core of my application (in a very basic test, I have 329901 calls
to __getitem__).

Oh well; I'll see if I can optimize the __getattr__ function with
minor tweaking. Thanks for your help.



More information about the Python-list mailing list