Inheriting from OrderedDict causes problem

Peter Otten __peter__ at web.de
Wed Feb 22 12:10:25 EST 2012


Bruce Eckel wrote:

> Notice that both classes are identical, except that one inherits from
> dict (and works) and the other inherits from OrderedDict and fails.
> Has anyone seen this before? Thanks.
> 
> import collections
> 
> class Y(dict):
>     def __init__(self, stuff):
>         for k, v in stuff:
>             self[k] = v
> 
> # This works:
> print Y([('a', 'b'), ('c', 'd')])
> 
> class X(collections.OrderedDict):
>     def __init__(self, stuff):
>         for k, v in stuff:
>             self[k] = v
> 
> # This doesn't:
> print X([('a', 'b'), ('c', 'd')])
> 
> """ Output:
> {'a': 'b', 'c': 'd'}
> Traceback (most recent call last):
>   File "OrderedDictInheritance.py", line 17, in <module>
>     print X([('a', 'b'), ('c', 'd')])
>   File "OrderedDictInheritance.py", line 14, in __init__
>     self[k] = v
>   File "C:\Python27\lib\collections.py", line 58, in __setitem__
>     root = self.__root
> AttributeError: 'X' object has no attribute '_OrderedDict__root'
> """

Looks like invoking OrderedDict.__init__() is necessary:

>>> from collections import OrderedDict
>>> class X(OrderedDict):
...     def __init__(self, stuff):
...             super(X, self).__init__()
...             for k, v in stuff:
...                     self[k] = v
...
>>> X([("a", "b"), ("c", "d")])
X([('a', 'b'), ('c', 'd')])





More information about the Python-list mailing list