[issue34314] Like __hash__, allow setting MyClass.__init__ to None to prevent it being called by type.__call__

Serhiy Storchaka report at bugs.python.org
Wed Aug 1 23:37:07 EDT 2018


Serhiy Storchaka <storchaka+cpython at gmail.com> added the comment:

Setting __hash__ to None doesn't do what you think. It doesn't prevent __hash__ from being called by hash(), instead it produces a TypeError.

>>> class A: __hash__ = None
... 
>>> hash(A())
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'A'

Actually the effect of special casing __hash__ is not raising a TypeError, but raising a TypeError with better error message. A TypeError was already raised before if set __hash__ to a non-callable. In 2.7:

>>> class A: __hash__ = None
... 
>>> hash(A())
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'NoneType' object is not callable


If you want to prevent an inherited __init__ from being called by types's __call__, you can define an __init__ with an empty body.

    def __init__(self, *args, **kwargs):
        pass

----------
nosy: +serhiy.storchaka

_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue34314>
_______________________________________


More information about the Python-bugs-list mailing list