Home

weakreffinalize

Weak reference finalization, commonly accessed via the Python function weakref.finalize, is a mechanism for performing cleanup actions when an object is about to be garbage collected. It provides a reliable alternative to relying on __del__ methods, especially in the presence of reference cycles or complex object lifetimes.

The basic usage involves calling weakref.finalize(obj, func, *args, **kwargs). This creates a Finalizer object that stores

Timing and guarantees are important considerations. The callback runs when the garbage collector determines that obj

Common use cases include releasing resources that are not tied to Python object lifetimes, such as closing

a
weak
reference
to
obj
and
retains
the
callback
function
along
with
its
arguments.
When
obj
becomes
unreachable,
the
finalizer
invokes
func(*args,
**kwargs)
exactly
once.
The
finalizer
can
be
detached
if
cleanup
should
be
postponed
or
canceled,
and
it
exposes
an
alive
attribute
to
check
whether
the
callback
is
still
pending.
is
dead,
which
depends
on
reference
counts
and
the
interpreter’s
GC
strategy.
The
exact
moment
is
not
predictable,
and
finalizers
may
not
run
at
interpreter
shutdown
or
after
a
process
termination.
Because
it
uses
a
weak
reference,
the
existence
of
the
finalizer
itself
does
not
keep
obj
alive.
files
or
sockets,
or
cleaning
up
external
handles
where
__del__
would
be
unreliable.
While
powerful,
weak
reference
finalization
should
be
used
cautiously:
finalizers
may
race
with
program
shutdown,
and
care
is
needed
to
avoid
raising
exceptions
during
finalization
or
creating
new
references
to
objects
being
collected.