Generic dictionary

Thorsten Kampe thorsten at thorstenkampe.de
Sun Nov 20 07:26:24 EST 2016


* Steve D'Aprano (Sun, 20 Nov 2016 21:10:08 +1100)
> 
> On Sun, 20 Nov 2016 08:27 pm, Thorsten Kampe wrote:
> 
> > I'd like to extend the dictionary class by creating a class that acts
> > like a dictionary if the class is instantiated with a dictionary and
> > acts like a "dictitem" ([(key1, value1), (key2, value2), ...]) if
> > instantiated with a list (that is dictitem).
> 
> I'm not sure exactly what you are trying to accomplish here. You want a
> single class that sometimes behaves like a dict, and sometimes behaves like
> a list? Not just any list, but specifically a list of tuples of two items.

Treating a list of tuples as a substitute for a dictionary is a well 
established idiom (think list(dict.items()) and dict()).
 
> Frankly, that sounds... weird. Generally speaking, classes don't behave
> differently according to how they are created.

I think, you misinterpreted my question. It's not about behaving 
differently but the opposite: a streamlined interface for the caller 
so the caller does not have to worry whether it uses a dict or a 
dictitem.

See my response to Peter:
The use case is an Equivalence class which creates a {invariant(x): 
[x, y, z] ...} dictionary. Since the Equivalence class should accept 
all kinds of key functions, I have to make sure that lists (which are 
not hashable), etc. can be handled as keys.

The GenericDict class allows the Equivalence class to be agnostic 
regarding the underlying data structure. It tries to create a 
dictionary and if that fails uses a dictitem. All method calls are 
the same because that's handled by GenericDict.

Thorsten




More information about the Python-list mailing list