views:

59

answers:

3

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?

+3  A: 

Only if something else does a del mod_x.x or a rebind at some point, or if the module itself becomes fully deleted.

Ignacio Vazquez-Abrams
+2  A: 

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 to mod_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.) a getattr(sys.modules[a], b) where string variables a and b happen 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...!-).

Alex Martelli
Thanks, that's what I thought. It means that the bug I am after lies somewhere else...
jldupont
+1  A: 

Once the module is imported it will be in the sys.modules dict so unless it is removed from there (which is possible though not standard practice) it will not be garbage collected.

So if you have a reason for wanting a module that has been loaded to be garbage collected you have to mess with sys.modules.

Tendayi Mawushe