Sub topic 4
Object lifetime, del, and finalizers
This chapter assumes you know that Python variables are names bound to objects, and that CPython frees most objects by reference counting. Both ideas come from earlier chapters. Here you will see exactly when an object's life ends, what del does, and why __del__ is a poor place for cleanup.
The life of an object
An object exists from the moment it is created until its reference count drops to zero. At that point CPython runs the object's finalizer, if it has one, and then releases its memory.
What del actually does
The del statement removes a name. It does not delete an object. The object is freed only if that was the last reference.
class Token:
def __init__(self, name):
self.name = name
def __del__(self):
print(f"finalizing {self.name}")
def work():
t = Token("local")
print("working")
a = Token("first")
b = a
del a
print("after del a") # object still alive through b
del b # last reference gone, __del__ runs here
print("after del b")
work() # local name t disappears when the function returns
print("done")The output is:
after del a
finalizing first
after del b
working
finalizing local
doneLocal names are released when a function returns, so objects referenced only by locals are finalized at that point. In CPython this timing is predictable. It is an implementation detail, though. Other interpreters such as PyPy do not free objects at the moment the count reaches zero.
Finalizers and their limits
__del__ is called a finalizer. It is not a destructor in the C++ sense, and it has several limits:
- It runs only when the object is about to be freed. You cannot call it on a schedule.
- An exception raised inside
__del__is printed to standard error and then ignored. The caller never sees it. - At interpreter shutdown, Python does not guarantee that
__del__runs for every remaining object. Modules and globals may already be partly torn down. - A reference kept elsewhere delays the call. A traceback stored from a caught exception holds the frames, and so their local objects, until the traceback is released.
- A finalizer can store
selfsomewhere and so resurrect the object. Since Python 3.4,__del__runs at most once per object, even if it is resurrected.
Better ways to clean up
Use a with statement when a resource has a clear scope. It releases the resource at a fixed point, whatever happens to the references.
When you need a callback tied to an object's lifetime, use weakref.finalize. It runs a function when the object is freed. It also runs at exit by default, and it does not keep the object alive.
import weakref
class Connection:
pass
conn = Connection()
weakref.finalize(conn, print, "connection closed")
del conn # prints "connection closed"The callback and its arguments must not refer to the object itself. If they did, the object would never reach a count of zero.
| Tool | Runs when | Good for |
|---|---|---|
| `with` block | The block exits | Files, locks, connections |
| `try` / `finally` | The block exits, even on error | One-off cleanup |
| `weakref.finalize` | The object is freed, or at exit | Cleanup tied to an object's lifetime |
| `__del__` | The object is freed, if at all | Rarely the right choice |
Exercise
A class defines __del__ that closes a file. A script catches an exception raised inside a method of an instance and stores the exception in a global list. Why might the file stay open long after the script no longer uses the instance, and what is a more reliable design?
Show answer
The stored exception holds its traceback, and the traceback holds the frames of the failed call. Those frames hold local names, including self, so the instance's reference count never reaches zero and __del__ does not run. A more reliable design makes the class a context manager, or uses with open(...) directly, so the file closes when the block exits regardless of references.