Inheriting dictionary

Simon Forman sajmikins at gmail.com
Wed Aug 19 05:27:39 CEST 2009


On Tue, Aug 18, 2009 at 6:08 PM, Simon Forman<sajmikins at gmail.com> wrote:
> On Aug 18, 3:44 pm, 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.
>
>
> I would consider something like the following:
>
>
> a = {1: "one", 2: "two", 4: "four"}
> b = {3: "three", 4: "foobar"}
>
>
> from functools import partial
>
>
> def getter(first, second, key):
>    try:
>        return first(key)
>    except KeyError:
>        return second(key)
>
>
> f = partial(getter, b.__getitem__, a.__getitem__)
>
>
> # Or, if you know you'll be getting a lot of KeyErrors, you
> # can use get() instead of __getitem__().
>
> def getter1(first, second, key, sentinel=None):
>    item = first(key, sentinel)
>    if item is sentinel:
>        item = second(key)
>    return item
>
> g = partial(getter1, b.get, a.__getitem__)
>
>
> HTH,
> ~Simon
> --
> http://mail.python.org/mailman/listinfo/python-list
>

Since you're going for speed the overhead of using partial (which
creates a wrapper object around the getter function) can be replaced
by something like this:

def makeGetter(first, second):
    def getter(key):
        try:
            return first(key)
        except KeyError:
            return second(key)
    return getter


f = makeGetter(b.__getitem__, a.__getitem__)



More information about the Python-list mailing list