I have tried inheriting from both collections.defaultdict
and collections.OrderedDict
like so:
class OrderedDefaultDict(defaultdict, OrderedDict): pass
and like so:
class OrderedDefaultDict(OrderedDict, defaultdict): pass
in order to created an ordered default dict (a class that should remember the order in which new default items were generated) but it seems to throw an error stating:
TypeError: multiple bases have instance lay-out conflict
I have read here that it's because they're both implemented in C. Upon disabling Python's C implementation of OrderedDict
by commenting this section in the collections
module:
try:
from _collections import OrderedDict
except ImportError:
# Leave the pure Python version in place.
pass
I have managed to inherit from both, but it does not seem to work as I expected. I have two questions then:
- Why can't you inherit from two classes written in C? I would understand if you wouldn't be able to inherit from any class written in C but why can you inherit from one and not from 2?
- Implementing my requested class would be easy by subclassing
OrderedDict
and overriding__getitem__()
to matchdefaultdict
's behavior. Is there a better way (preferably within the standard library) to mimick the same behavior? Or is subclassingOrderedDict
the most optimal? (subclassingdefaultdict
is possible too but implementing it is is probably easier usingOrderedDict
)
The first question is the important of the two as implementing it myself by subclassing OrderedDict
shouldn't pose a problem.