I defined this function:
def caller_class():
loc = inspect.stack()[1][0].f_locals
cls = loc.get("__class__", None)
return cls
Then tested it:
class A:
def __init__(self):
print(caller_class())
A()
The output was:
None
<A object at 0x0350BCE8>
However, I tweaked the test:
class A:
def __init__(self):
__class__
print(caller_class())
A()
And the result was so different:
<class '__main__.A'>
<__main__.A object at 0x0350BEE0>
The only change was I added a __class__ mention in the __init__ function. Yet, the frame all of a sudden had a __class__ attribute. Why does this strange behavior occur?