I don't know why this doesn't work:
I'm using the odict class from PEP 372, but I want to use it as a __dict__
member, i.e.:
class Bag(object):
def __init__(self):
self.__dict__ = odict()
But for some reason I'm getting weird results. This works:
>>> b = Bag()
>>> b.apple = 1
>>> b.apple
1
>>> b.banana = 2
>>> b.banana
2
But trying to access the actual dictionary doesn't work:
>>> b.__dict__.items()
[]
>>> b.__dict__
odict.odict([])
And it gets weirder:
>>> b.__dict__['tomato'] = 3
>>> b.tomato
3
>>> b.__dict__
odict.odict([('tomato', 3)])
I'm feeling very stupid. Can you help me out?
Everything in sykora's answer is correct. Here's an updated solution with the following improvements:
a.__dict__
directlycopy.copy()
==
and!=
operatorscollections.OrderedDict
from Python 2.7....
The closest answer to your question that I can find is at http://mail.python.org/pipermail/python-bugs-list/2006-April/033155.html.
Basically, if
__dict__
is not an actualdict()
, then it is ignored, and attribute lookup fails.The alternative for this is to use the odict as a member, and override the getitem and setitem methods accordingly.
If you're looking for a library with attribute access to OrderedDict, the orderedattrdict package provides this.
Disclosure: I authored this library. Thought it might help future searchers.