I want to write a container class which
- allows both indexing (in the dictionary style), e.g.
data['a']
and attribute-like access e.g.data.a
; this is addressed here - preserves the order in which entries where added, e.g. by subclassing
collections.OrderedDict
; this is addressed here
I adapted the solution for 1. to subclass collections.OrderedDict
instead of dict
but it does not work; see below.
from collections import OrderedDict
class mydict(OrderedDict):
def __init__(self, *args, **kwargs):
super(mydict, self).__init__(*args, **kwargs)
self.__dict__ = self
D = mydict(a=1, b=2)
#D['c'] = 3 # fails
D.d = 4
#print D # fails
The two lines with the failure comment cause the following errors:
print D
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/collections.py", line 176, in __repr__
return '%s(%r)' % (self.__class__.__name__, self.items())
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/collections.py", line 113, in items
return [(key, self[key]) for key in self]
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/collections.py", line 76, in __iter__
root = self.__root
AttributeError: 'struct' object has no attribute '_OrderedDict__root'
and
D['c'] = 3
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/collections.py", line 58, in __setitem__
root = self.__root
AttributeError: 'mydict' object has no attribute '_OrderedDict__root'
Is there a solution to this ? Can the __init__
function be patched ?