[Python-Dev] bug with dict? (original) (raw)

tomer filiba tomerfiliba at gmail.com
Wed Apr 19 20:59:10 CEST 2006


overriding getattr and setattr has several negative side effects, for example:

so i had an idea -- why not just replace dict? this does not affect the MRO. i wrote an AttrDict class, which is like dict, only it allows you to acces its keys as attributes. i later saw something like this on the python cookbook as well.

class AttrDict(dict): def init(self, *a, **k): dict.init(self, *a, **k) self.dict = self

this code basically causes getattr/setattr to use getitem/setitem: a =AttrDict() a["blah"] = 5 a.yadda = 6 print a.blah print a["yadda"]

which is exactly what i wanted. now, i thought, instead of overriding getattr/setattr, i'd just write a class that overrides getitem/setitem. for example:

old way

class A(object): def getattr(self, name): return 5 a = A() print a.xyz # 5

new way

class mydict(dict): def getitem(self, key): return 5 class A(object): def init(self): self.dict = mydict() a = A() print a.xyz # should print 5

but lo and behold, python does not call my overriden method. it just bypasses it and always calls the original dict's method. i made several tests, trying to see if it calls contains, placed hooks on getattribute, but nothing from my overriden methods is ever called. this is probably because the C implementation calls PyDict_GetItem or whatever directly...

i think it's a bug. i should be able to override the getitem of my dict. it breaks the polymorphism of python-level objects! on the one hand, i'm allowed to change dict to any object that derives from dict, but i'm not allowed to override it's methods!

python must either disable assigning to dict, or be willing to call overriden methods, not silently ignore mine.

-tomer -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/python-dev/attachments/20060419/67fac888/attachment.htm



More information about the Python-Dev mailing list