1

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.

eepp
  • 7,255
  • 1
  • 38
  • 56
  • Hey, this was marked as duplicate, but the "duplicate" question is not the same at all. I know what `__del__()` does, that's not the point. I have a very specific question here about nested class references. – eepp Mar 28 '19 at 20:01
  • Well, for starters, classes keep track of their subclasses. So if you check `object.__subclasses__()` you'll see three different Foo classes (same name, different objects). There likely are other places as well. – juanpa.arrivillaga Mar 28 '19 at 20:26

0 Answers0