[docs] [issue15360] Behavior of assigning to __dict__ is not documented

Davide Rizzo report at bugs.python.org
Sat Jul 21 00:37:53 CEST 2012


Davide Rizzo <sorcio at gmail.com> added the comment:

Amaury, I don't honestly know, I would have proposed something otherwise.

I have been advised on #python (Freenode) not to assign to obj.__dict__ because its behaviour changes between versions and implementations, but I wouldn't know what has changed between CPython version.

One obscure thing is what can be assigned to __dict__. For class dicts no assignment is allowed. Object dicts can be assigned dict objects. If you try to assign a non-dict mapping it will complain.

However you can assign a dict-derived object, something like:

class SillyDict(dict):
    def __getitem__(self, key):
        return "hello"

obj.__dict__ = SillyDict()

Unfortunately accessing the attributes of obj will still use PyDict_* functions, thus ignoring any magic methods.

PyPy's behavior is slightly different. A class __dict__ attribute still is read only, but you can assign any mapping object to an object __dict__.

----------

_______________________________________
Python tracker <report at bugs.python.org>
<http://bugs.python.org/issue15360>
_______________________________________


More information about the docs mailing list