Python Glossary Русский

Python 3.4+weakrefterm

weakref.finalize

finalization

Registers a function to be called when an object is garbage collected, or at program exit. A reliable replacement for __del__.

Syntax

f = weakref.finalize(obj, func, *args, **kwargs)

The main mistake is passing the object's own method, or a lambda that captures the object, to finalize: the finalizer holds strong references to its function and arguments, so the object never dies. Pass what cleanup needs (a file name, a descriptor), not the object itself. A finalizer runs once; f.alive tells whether it is still pending, and f() runs it early — like close() on a resource.

Examples

import weakref
class TempFile:
    pass
t = TempFile()
f = weakref.finalize(t, print, 'cleanup')
print(f.alive)  # → True
del t
# → cleanup
print(f.alive)  # → False

See also

Open in the full glossarydocs.python.orgReport an inaccuracy