Why can't I inherit from dict AND Exception in Python?
multiple-inheritance, python
Solution
Both `Exception` and `dict` are implemented in C.
I think you can test this the follwing way:
>>> class C(object): pass
...
>>> '__module__' in C.__dict__
True
>>> '__module__' in dict.__dict__
False
>>> '__module__' in Exception.__dict__
False
Since `Exception` and `dict` have different ideas of how to store their data internally, they are not compatible and thus you cannot inherit from both at the same time.
In later versions of Python you should get an Exception the moment you try to define the class:
>>> class foo(dict, Exception):
... pass
...
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: Error when calling the metaclass bases
multiple bases have instance lay-out conflict
Problem
I got the following class : ``` class ConstraintFailureSet(dict, Exception) : """ Container for constraint failures. It act as a constraint failure itself but can contain other constraint failures that can be accessed with a dict syntax. """ def __init__(self, **failures) : dict.__init__(self, failures) Exception.__init__(self) print isinstance(ConstraintFailureSet(), Exception) True raise ConstraintFailureSet() TypeError: exceptions must be classes, instances, or strings (deprecated), not ConstraintFailureSet ``` What the heck ? And the worst is that I can't try super() since Exception are old based class... EDIT : And, yes, I've tried to switch the order of inheritance / init. EDIT2 : I am using CPython 2.4 on Ubuntu8.10. You newer know is this kind of infos is usefull ;-). Anyway, this little riddle has shut the mouth of 3 of my collegues. You'd be my best-friend-of-the day...