* Peter Otten (Sun, 20 Nov 2016 10:43:01 +0100) > > 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). > > > > The code (see extract at bottom) works well but it contains a lot of > > "if this is a dictionary then do as a dictionary already does" > > boilerplate code". How can I "inherit"(?)/"subclass"(?)/derive from > > dict so I don't have to write the code for the dictionary case? > > Hm. > > def GenericDict(dict_or_items): > if isinstance(dict_or_items, dict): > return dict(dict_or_items) > else: > return SimpleGenericDictWithOnlyTheFalseBranchesImplemented( > dict_or_items > )
That would be a kind of factory function for the class? > > ``` > > class GenericDict: > > """ > > a GenericDict is a dictionary or a list of tuples (when the keys > > are not hashable) > > """ > > def __init__(inst, generic_dict): > > inst._generic = generic_dict > > > > def __getitem__(inst, key): > > if isinstance(inst._generic, dict): > > return inst._generic[key] > > else: > > return inst.values()[inst.keys().index(key)] > > It's not obvious why you'd ever want that. What's the use case? 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. Treating a list of tuples as a substitute for a dictionary is a well established idiom (think list(dict.items()) and dict()). 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 -- https://mail.python.org/mailman/listinfo/python-list