Consider this (Python 3):
class M(type):
def __new__(cls, name, bases, dct):
print('creating class {}'.format(name))
return super().__new__(cls, name, bases, dct)
def __del__(cls):
print('deleting class {}'.format(cls.__name__))
def func():
class A(metaclass=M):
pass
func()
func()
func()
print('end')
The output is:
creating class A
creating class A
creating class A
end
deleting class A
deleting class A
deleting class A
This shows that once the function's nested class is created (when calling func()
), something holds a reference on it even when the function returns.
What exactly holds such a reference? Is there any way to access the created class after func()
returns?
Note: sys.getrefcount(A)
just before the function returns returns 5.