__dict__ strangeness

Alex Martelli aleaxit at yahoo.com
Sat Mar 18 12:39:44 EST 2006


Georg Brandl <g.brandl-nospam at gmx.net> wrote:

> can someone please tell me that this is correct and why:

IMHO, it is not correct: it is a Python bug (and it would be nice to fix
it in 2.5).

> >>> class C(object):
> ...     pass
> ...
> >>> c = C()
> >>> c.a = 1
> >>> c.__dict__
> {'a': 1}
> >>> c.__dict__ = {}
> >>> c.a
> Traceback (most recent call last):
>   File "<stdin>", line 1, in ?
> AttributeError: 'C' object has no attribute 'a'

So far so good, I think we agree;-).

> >>> class D(object):
> ...     __dict__ = {}
> ...
> >>> d = D()
> >>> d.a = 1
> >>> d.__dict__
> {}
> >>> d.__dict__ = {}
> >>> d.a
> 1

Yep, that's the bug, fully reproducible in 2.3 and 2.4.  FWIW, mucking
around with gc.getreferrers (with a more uniquely identifiable value for
d.a;-) shows a dictionary "somewhere" with keys 'a' and '__dict__'...


Alex



More information about the Python-list mailing list