weakref.finalize Runs Cleanup On Collection
Register weakref.finalize callbacks so cleanup runs when an object is collected, without keeping the object alive or leaking resources.
Code
import gc
import weakref
class Buffer:
def __init__(self, name: str) -> None:
self.name = name
def __repr__(self) -> str:
return 'Buffer(' + self.name + ')'
def main() -> None:
events = []
def release(name: str) -> None:
events.append('released:' + name)
def build() -> weakref.finalize:
buf = Buffer('scratch')
# finalize:对象被回收时回调,不延长生命周期
handle = weakref.finalize(buf, release, buf.name)
print('alive before collection:', handle.alive)
return handle
handle = build()
print('after builder returns, alive:', handle.alive)
gc.collect()
print('after gc, alive:', handle.alive)
print('events:', events)
# detach:取消回调并返回原参数
other = Buffer('kept')
handle2 = weakref.finalize(other, release, other.name)
print('detached args:', handle2.detach())
print('events after detach:', events)
if __name__ == '__main__':
main()How it works
weakref.finalize Runs Cleanup On Collection keeps everything in the class Buffer and the functions __init__, __repr__, main and release.
Points of care
- Dependency check:
gcandweakref— not built-in, must be present in the project.
Using it
The run emits 3 labeled sections — alive before collection:, after builder returns, alive:, after gc, alive: — one per step.
There are 2 calls inside main — release and build — executed top to bottom.
Key statements
def __init__(self, name: str) -> None:
self.name = name
def release(name: str) -> None:
events.append('released:' + name)
def build() -> weakref.finalize:
buf = Buffer('scratch')
# finalize:对象被回收时回调,不延长生命周期
handle = weakref.finalize(buf, release, buf.name)
print('alive before collection:', handle.alive)
return handle
Interactive Tools for This Topic
FAQ
- What does weakref.finalize Runs Cleanup On Collection print when run?
- Invoke the file as-is — the `alive before collection:`, `after builder returns, alive:`, `after gc, alive:` prefixes identify which step printed each line.
Report a problem with this exampleOpens a pre-filled issue on GitHub.