[Python-Dev] Possible undefined behavior on creating a method named "__dict__"

Joao S. O. Bueno jsbueno at python.org.br
Wed Apr 11 07:21:01 EDT 2018


I just came across a code snippet that
would define a method with the "__dict__" name  - like in:

class A:
    def __dict__(self):
         return ()

The resulting class's instances can be assigned
dynamic attributes as usual, but one can never acess
its actual local variables through instance.__dict__ -
the method is retrieved instead.  Calling "vars" will also fail
on objects of this class.

This behavior is weird, and I believe is actually a side-effect
of implementation details on CPython.

I am not sure whether it shoud just:
1 - be left as is - whoever reuses __dict__ as a method had it coming
2 - document  CPythn behavior
3 - file that as a bug to disallow __dict__ override in class declaration
4 - file that as a bug to not-create class __dict__ when one is explictly
      created in Python code (the same that happens when one have "__slots__".

I have the feeling that (1) is just good - but then, I am at least
posting this e-mail here.

Similar weird things go when one creates a method named "__class__",
and possible other names.

(I just checked that pypy3 mimics the behavior)

   js
 -><-


More information about the Python-Dev mailing list