baloan wrote:
On Oct 22, 6:34 am, "Gabriel Genellina" <gagsl-...@yahoo.com.ar>
wrote:
class AttrDict(dict):
     """A dict whose items can also be accessed as member variables."""
     def __init__(self, *args, **kwargs):
         dict.__init__(self, *args, **kwargs)
         self.__dict__ = self
     def copy(self):
         return AttrDict(self)
     def __repr__(self):
         return 'AttrDict(' + dict.__repr__(self) + ')'
     @classmethod
     def fromkeys(self, seq, value = None):
         return AttrDict(dict.fromkeys(seq, value))
Looks fine as long as nobody uses an existing method name as adictionary key:

py> d = AttrDict({'name':'value'})
py> d.items()
[('name', 'value')]
py> d = AttrDict({'items': [1,2,3]})
py> d.items()
Traceback (most recent call last):
   File "<stdin>", line 1, in <module>
TypeError: 'list' object is not callable

(I should have included a test case for this issue too).
Of course, if this doesn't matter in your application, go ahead and use it. Just be aware of the problem.

--
Gabriel Genellina

I see two ways to avoid collisions with existing method names:

1. (easy, reduced functionality) override __setattr__ and __init__,
test for keys matching existing method names, throw an exception if
exists (KeyError).
2. (complex, emulates dict) override __setattr__ and __init__, test
for keys matching existing method names, and store those keys in a
shadow dict. More problems arise when thinking about how to choose
access between dict method names and item keys.

--
Andreas Balogh
baloand at gmail dot com

That was indeed my last post. It seems for this thread Google does not sort correctly descending "creation time fo the last post". This thread was not visible as "new" when I posted...

Regards, Andreas

--
Andreas Balogh
baloand (at) gmail.com
--
http://mail.python.org/mailman/listinfo/python-list

Reply via email to