Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using an ordered dict as object dictionary in python

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?

like image 957
itsadok Avatar asked Jan 18 '09 12:01

itsadok


2 Answers

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 actual dict(), 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.

>>> class A(object) :
...     def __init__(self) :
...             self.__dict__['_odict'] = odict()
...     def __getattr__(self, value) :
...             return self.__dict__['_odict'][value]
...     def __setattr__(self, key, value) :
...             self.__dict__['_odict'][key] = value
... 
>>> a = A()
>>> a
<__main__.A object at 0xb7bce34c>
>>> a.x = 1
>>> a.x
1
>>> a.y = 2
>>> a.y
2
>>> a.odict
odict.odict([('x', 1), ('y', 2)])
like image 79
sykora Avatar answered Oct 29 '22 07:10

sykora


Everything in sykora's answer is correct. Here's an updated solution with the following improvements:

  1. works even in the special case of accessing a.__dict__ directly
  2. supports copy.copy()
  3. supports the == and != operators
  4. uses collections.OrderedDict from Python 2.7.

...

from collections import OrderedDict

class OrderedNamespace(object):
    def __init__(self):
        super(OrderedNamespace, self).__setattr__( '_odict', OrderedDict() )

    def __getattr__(self, key):
        odict = super(OrderedNamespace, self).__getattribute__('_odict')
        if key in odict:
            return odict[key]
        return super(OrderedNamespace, self).__getattribute__(key)

    def __setattr__(self, key, val):
        self._odict[key] = val

    @property
    def __dict__(self):
        return self._odict

    def __setstate__(self, state): # Support copy.copy
        super(OrderedNamespace, self).__setattr__( '_odict', OrderedDict() )
        self._odict.update( state )

    def __eq__(self, other):
        return self.__dict__ == other.__dict__

    def __ne__(self, other):
        return not self.__eq__(other)
like image 42
Stuart Berg Avatar answered Oct 29 '22 06:10

Stuart Berg