I've read Why is Python 3.x's super() magic? and understand that using super or __class__ in a method will automagically create a __class__ cell variable for that method:
class Demo:
def meth(self):
super().meth()
>>> Demo.meth.__closure__
(<cell at 0x7f4572056138: type object at 0x564bda0e5dd8>,)
>>> Demo.meth.__closure__[0].cell_contents
<class '__main__.Demo'>
And as far as I know, cells are used to hold closure variables and can be freely modified:
def outer():
x = 3
def inner():
print(x)
x = 5
return inner
inner = outer()
inner() # output: 5
>>> inner.__closure__
(<cell at 0x7f2183a5e138: int object at 0x7f2184600460>,)
But trying to reassign the value of the __class__ cell makes super throw a strange error:
class Demo:
def meth(self):
__class__ = Demo
super().meth()
Demo().meth()
Traceback (most recent call last):
File "untitled.py", line 8, in <module>
Demo().meth()
File "untitled.py", line 6, in meth
super().meth()
RuntimeError: super(): __class__ cell not found
Why does this happen? Why can't __class__ be reassigned like other closure variables?