On this page
weakref.finalize
Prev: weakref.CallableProxyType | Up: weakref | Next: weakref.getweakrefcount
Rel: weakref.CallableProxyType, weakref.getweakrefcount, weakref.getweakrefs, weakref.proxy
Ref: docs.python.org — weakref.finalize
Tags: #public #python3 #stdlib #weakref
Import
import weakref
from weakref import finalize
Signature & Overview
weakref.finalize(obj, func, /, *args, **kwargs)
Class for finalization of weakrefable objects finalize(obj, func, *args, **kwargs) returns a callable finalizer object which will be called when obj is garbage collected. The
Methods & Attributes
finalize.alive(...)— Whether finalizer is alivefinalize.atexit(...)— Whether finalizer should be called at exitfinalize.detach(self)— If alive then mark as dead and return (obj, func, args, kwargs); otherwise return Nonefinalize.peek(self)— If alive then return (obj, func, args, kwargs); otherwise return None
Usage
import weakref
log: list[str] = []
class Res: pass
r = Res()
fin = weakref.finalize(r, log.append, 'cleaned')
del r
assert log == ['cleaned'] and not fin.alive
Gotchas
- Safer replacement for
__del__: Guarantees at-most-once cleanup and works cleanly even at interpreter exit.
REPL Inspect
from weakref import finalize
help(finalize)
Linked from
- tuts/python3/stdlib_module/weakref
- tuts/python3/stdlib_module/weakref/CallableProxyType
- tuts/python3/stdlib_module/weakref/getweakrefcount
- tuts/python3/stdlib_module/weakref/getweakrefs
- tuts/python3/stdlib_module/weakref/proxy
- tuts/python3/stdlib_module/weakref/ProxyType
- tuts/python3/stdlib_module/weakref/ref
- tuts/python3/stdlib_module/weakref/ReferenceType
- tuts/python3/stdlib_module/weakref/WeakKeyDictionary
- tuts/python3/stdlib_module/weakref/WeakMethod
- tuts/python3/stdlib_module/weakref/WeakSet
- tuts/python3/stdlib_module/weakref/WeakValueDictionary
Related notes
- tuts/python3/stdlib_module/weakref/CallableProxyType Linked here; links to this page; shared tags: #stdlib, #weakref
- tuts/python3/stdlib_module/weakref/getweakrefcount Linked here; links to this page; shared tags: #stdlib, #weakref
- tuts/python3/stdlib_module/weakref/getweakrefs Linked here; links to this page; shared tags: #stdlib, #weakref
- tuts/python3/stdlib_module/weakref/proxy Linked here; links to this page; shared tags: #stdlib, #weakref
- tuts/python3/stdlib_module/weakref Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/weakref/ProxyType links to this page; shared tags: #stdlib, #weakref
- tuts/python3/stdlib_module/weakref/ref links to this page; shared tags: #stdlib, #weakref
- tuts/python3/stdlib_module/weakref/ReferenceType links to this page; shared tags: #stdlib, #weakref
- tuts/python3/stdlib_module/weakref/WeakKeyDictionary links to this page; shared tags: #stdlib, #weakref
- tuts/python3/stdlib_module/weakref/WeakMethod links to this page; shared tags: #stdlib, #weakref