Dictionary inheritance

Devan L devlai at gmail.com
Fri Aug 12 21:57:41 CEST 2005


Talin wrote:
> I want to make a dictionary that acts like a class, in other words,
> supports inheritance: 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.
>
> Now, I realize its fairly trivial to code something like this using
> UserDict, but given that classes and modules already have this behavior,
> is there some built-in type that already does this?
>
> (This is for doing nested symbol tables and such.)
>
> ---
>
> 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:") ?
>
> -- Talin

Dictionaries aren't classes? I wasn't aware of that. Anyways, what
you're looking for, I think is a class that emulates a dictionary.
Probably you should just have some attribute that references a bigger
dictionary.

bigger_dict =
{'foo':1,'baz':2,'bar':3,'foobar':4,'foobaz':5,'foobazbar':6}
smaller_dict = {'spam':1,'ham':2,'bacon':3,'eggs':4}
smaller_dict.fallback = bigger_dict

and then the __getitem__ method might look something like

def __getitem__(self, key):
    if self.has_key(key):
        return self[key]
    else:
        return self.fallback[key]




More information about the Python-list mailing list