Let’s say I have a module mod_x like the following:
class X:
pass
x=X()
Now, let’s say I have another module that just performs import mod_x, and goes about its business. The module variable x will not be referenced further during the lifecycle of the interpreter.
Will the class instance x get garbage collected at any point except at the termination of the interpreter?
No, the variable will never get garbage-collected (until the end of the process), because the module object will stay in
sys.modules['mod_x']and it will have a reference tomod_x.x— the reference count will never drop to 0 (until all modules are removed at the end of the program) and it’s not an issue of “cyclycal garbage” — it’s a perfectly valid live reference, and proving that nobody every does (e.g.) agetattr(sys.modules[a], b)where string variablesaandbhappen to be worth'mod_x'and'x'respectively is at least as hard as solving the halting problem;-). (“At least” since more code may be about to be dynamically loaded at any time…!-).