Sub topic 4
Object lifetime, del, and finalizers
This chapter assumes you know that CPython frees most objects when their reference count reaches zero (the previous chapter on reference counting), and that you are comfortable with classes and exceptions. It covers what del does, when __del__ runs, and what to use when you need reliable cleanup.
The lifetime of an object
An object is created when its constructor runs. It stays alive while at least one strong reference points to it. When the last reference goes away, CPython runs the object's finalizer, if it has one, and then releases its memory.
Three events can drop a reference: a name is rebound, a name is deleted, or a name goes out of scope.
What `del` does
The del statement removes a name. It does not destroy an object. The object is freed only if that name held the last reference.
class Token:
def __init__(self, label):
self.label = label
def __del__(self):
print(f"finalizing {self.label}")
a = Token("A")
b = a
del a
print("after del a") # the object is still alive through b
del b # prints "finalizing A" here
print("after del b")The output is:
after del a
finalizing A
after del bdel also works on list items, dictionary keys, and attributes. In each case it removes a reference from a container or namespace, and the same rule applies.
Rebinding a name has the same effect as del on the old value. The old object is released after the right-hand side has been evaluated:
t = Token("one")
t = Token("two") # "one" is finalized here, after Token("two") existsFunction locals are released when the function returns:
def work():
t = Token("local")
print("working")
work()
print("done")This prints working, then finalizing local, then done. In CPython this timing is dependable. Other implementations such as PyPy do not free objects the moment the count drops, so code that relies on this timing is not portable.
Hidden references that extend a lifetime
An object you think is gone may still be referenced. Common causes:
- An exception that you stored keeps its traceback. The traceback keeps every frame on the call stack, and each frame keeps its local variables.
- A list, dictionary, cache, or global that you forgot about.
- A closure that captured the variable.
- The interactive interpreter's
_variable, which holds the last result.
The as name in an except clause is deleted when the block ends, to avoid a cycle between the exception and its own frame:
try:
raise ValueError("bad")
except ValueError as e:
pass
print("e" in dir()) # False: e was deleted at the end of the except blockIf you need the exception after the block, assign it to another name. Clear that name when you are done so the traceback and its frames can be freed.
Finalizers: `__del__`
__del__ is a method that CPython calls just before it destroys an instance. It is called a finalizer. It is not a destructor in the C++ sense, because it does not free the memory. CPython does that afterwards.
You rarely need to write one. Memory is freed for you, so __del__ only matters when an object owns something outside Python's heap, such as a file descriptor or a network connection. Even then, there are better tools, covered below.
Rules you must know
- Timing is guaranteed only for simple cases. In CPython, a non-cyclic object is finalized as soon as its count reaches zero. An object in a reference cycle is finalized later, when the cyclic collector runs, and you do not control when.
- Exceptions are not propagated. If
__del__raises, Python prints a message to standard error and carries on. Your code never sees the error. - It runs at most once per object. Since Python 3.4 (PEP 442), an object whose finalizer has already run is not finalized again.
- It may not run at all. At interpreter exit, objects that are still alive may not be finalized. If the process is killed or calls
os._exit(), no finalizers run. - It runs in unpredictable contexts. It can be called in the middle of any bytecode that drops a reference, in any thread. Keep it short and do not take locks that other code may hold.
Here is rule 2 in action:
class Bad:
def __del__(self):
raise RuntimeError("boom")
x = Bad()
del x
print("still running")Standard error shows Exception ignored in: <function Bad.__del__ at 0x...> followed by a traceback. Then still running is printed. Because the error does not stop the program, a failing cleanup can go unnoticed.
Resurrection
A finalizer receives self, so it can store self somewhere and make the object reachable again. This is called resurrection. The object returns to the alive state in the diagram above.
saved = []
class Phoenix:
def __del__(self):
print("__del__ called")
saved.append(self)
p = Phoenix()
del p
print(len(saved)) # 1: the object came back
saved.pop() # drops the last reference again
print(len(saved)) # 0__del__ called appears only once, even though the object was freed twice. That is rule 3. Resurrection is almost always a bug or a hack. Avoid it, but know it exists, because it explains why CPython checks the reference count again after running a finalizer.
Finalizers and cycles
Before Python 3.4, objects with __del__ in a reference cycle could not be collected, because the collector did not know which finalizer to run first. They were parked in gc.garbage. Modern CPython finalizes such objects and then frees them, so gc.garbage is normally empty. Cycles are covered in the next chapter. The point here is that the order in which finalizers run inside a cycle is not defined, so a finalizer must not assume that other objects it refers to are still usable.
Shutdown
When the interpreter exits, it tears down modules and clears their globals. A __del__ that runs during this phase may find that module-level names such as os or logging have already become None. This produces confusing errors from code that works at any other time. Do not depend on __del__ for anything that must happen before the program ends.
Better ways to clean up
Use an explicit tool when cleanup matters.
| Tool | When it runs | Use it for |
|---|---|---|
| `with` and `__enter__`/`__exit__` | At the end of the block, even on error | Files, locks, connections with a clear scope |
| `try`/`finally` | At the end of the block, even on error | One-off cleanup without a new class |
| `weakref.finalize` | When the object is freed, or at exit | Cleanup tied to an object whose lifetime you do not control |
| `atexit.register` | At normal interpreter exit | Process-wide cleanup |
| `__del__` | When the object is freed (timing varies) | A last-resort safety net |
A context manager makes the lifetime explicit, so you do not depend on reference counts:
class Connection:
def __init__(self, name):
self.name = name
self.open = True
def close(self):
if self.open:
print("closing", self.name)
self.open = False
def __enter__(self):
return self
def __exit__(self, exc_type, exc, tb):
self.close()
with Connection("db") as conn:
print("using", conn.name)
print(conn.open) # FalseThe close method can be called more than once without harm. Make cleanup methods idempotent so that a context manager and a safety net can both call them.
`weakref.finalize`
weakref.finalize registers a callback that runs when an object is freed. Unlike __del__, the callback is a separate function, it runs at most once, and it is also called at interpreter exit by default.
import weakref
class Resource:
def __init__(self, name):
self.name = name
def release(name):
print("releasing", name)
res = Resource("socket")
fin = weakref.finalize(res, release, res.name)
print(fin.alive) # True
del res # prints "releasing socket"
print(fin.alive) # FalsePass the data the callback needs as arguments (here res.name). Do not pass res itself or a bound method of it. That would store a strong reference to the object inside the finalizer, and the object could then never be freed.
A common pattern combines the tools. The class offers close() and context-manager support for normal use, and it registers a weakref.finalize so the resource is still released if the caller forgets.
Checking lifetimes while debugging
To confirm when an object dies, hold a weak reference to it and test whether it still resolves. This does not extend the lifetime. It also avoids adding __del__ just to observe behavior, because adding a finalizer changes how the object is handled.
import weakref
class Probe:
pass
obj = Probe()
ref = weakref.ref(obj)
print(ref() is obj) # True
del obj
print(ref()) # None in CPython: the last strong reference is goneIf ref() is not None after you expect the object to be gone, search for the extra reference: a list, a cache, a closure, a stored exception, or a cycle waiting for the collector.
Exercise
A class defines __del__ that prints a message. You run a = Obj(); b = a; del a. Does the message appear? What must happen for it to appear, and what happens if __del__ raises an exception at that point?
Show answer
The message does not appear after del a, because del only removes the name a, and b still refers to the object. The reference count drops from 2 to 1. The message appears when the last reference is dropped, for example del b, rebinding b, or the end of the scope that holds b. If __del__ raises an exception, Python prints "Exception ignored in ..." with a traceback to standard error and continues. The exception is not raised in the code that dropped the reference.
Exercise
You wrote fin = weakref.finalize(res, res.cleanup) and res is never freed even after you del res. Why, and how do you fix it?
Show answer
res.cleanup is a bound method, and a bound method holds a strong reference to res. The finalizer therefore keeps the object alive, so its count never reaches zero. Fix it by passing a plain function and the data it needs, for example weakref.finalize(res, release, res.name), so that the callback holds no reference to res.