Skip to content Skip to sidebar Skip to footer

Python: Weakref.finalize Not Run If Background Threads Are Alive

I wanted to use weakref.finalize to cleanup some background threads when an object goes out of sight, but the finalizer is not run (edit:) when the object is in the module scope. N

Solution 1:

As noted by @quamrana, module level objects only get garbage collected when the module is unloaded, so when the interpreter exits in practice.

Unfortunately, active threads also live in the loaded threading module with a refcount > 0, which prevents the current module from being unloaded and therefore the object from being garbage collected...

So the only way to ensure the object is gc is to scope the variable or make sure the threads timeout by themselves.

Solution 2:

You just need a way to make a go out of scope:

def main():
    a =A()
    # when main exits, a will be garbage collectedmain()

Output:

finalizing

Post a Comment for "Python: Weakref.finalize Not Run If Background Threads Are Alive"