Prefer Explicit Cleanup to Finalization
Core idea
Object reclamation and resource release are separate concerns. with and try/finally give lexical cleanup for resources. weakref.finalize offers a fallback callback that can be invoked explicitly at most once; it must not retain the object through a bound method or closure. del timing and shutdown ordering are not reliable cleanup contracts.
from io import StringIOf=StringIO('data')try: with f: raise ValueError('demo')except ValueError: print(f.closed)The context manager closes the stream when the exception leaves the block.
Expected output:
TrueInvoke an independent finalizer
import weakrefclass Resource: passx=Resource(); events=[]f=weakref.finalize(x, events.append, 'cleanup')f(); f()print(events, f.alive)Explicit invocation is deterministic; the second call does not repeat cleanup.
Expected output:
['cleanup'] FalseCommon mistake
Passing x.close to finalize(x, ...) can keep x alive through the bound method. Separate cleanup state from the referent.
Practice
Build a context manager with an event list; trigger an error inside it and verify the release event.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Finalization and cleanup
Check your understanding of finalization and cleanup.
What is printed?
from io import StringIOf=StringIO()with f: passprint(f.closed)What is printed?
import weakrefclass A: passa=A(); f=weakref.finalize(a,lambda: 8)print(f(),f())Which is the primary resource cleanup mechanism?
What should a finalizer callback avoid retaining?