Search code examples
cpythonpython-internals

What sets nb_bool in CPython?


By default, nb_bool slot on the Python type object should not exist. Otherwise, if the default slot_nb_bool exists, upon invocation, it will cause infinite recursion when __len__ is defined.

If so, what sets nb_bool in the following scenario?

class A:
  pass
A.__bool__ = lambda x: 0
assert not A()

Type object has no descriptor set for __bool__, and metaclass __setattr__ does not seem to be handling it according to CPython source.


Solution

  • type's tp_setattro slot (__setattr__) does handle it.

    Upon setting an attribute on a class, type_setattro is called.

    It checks if the attribute is a dunder method. If it is, it updates the appropriate slot.