[Python-Dev] bug with __dict__?

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:
* inside__getattr__/__setattr__ you have to use self.__dict__["attr"]
instead of self.attr
* it's easy to get stack overflow exceptions when you do something wrong
* you must remember to call the super's [get/set]attr or the MRO is broken
* when deriving from a class that overrides one of the speical methods, you
usually
need to override the special function of your class as well, to allow some
"local storage"
for yourself

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