An object lives while something is looking at it. From that one sentence you can derive both why with in Python really closes the file and why Python has a GIL. The two most discussed properties of the language are consequences of one decision.
Commit to an output and a reason before you open the answer.
class Res:
def __init__(self, n): self.n = n
def __del__(self): print(f"closed {self.n}")
def work():
r = Res("A")
print("working")
work()
print("after work")
working
closed A
after workThe question is not “what gets printed” but at which moment — and why exactly then.import sys
x = []
print(sys.getrefcount(x))
def f(o):
return sys.getrefcount(o)
print(f(x))
2
3There is one name, yet the count shows two. Then three.for line in open("data.txt"):
process(line)
# is the file closed at this point?
class Node:
def __init__(self, n): self.n = n; self.peer = None
def __del__(self): print(f"deleted {self.n}")
a = Node(1); b = Node(2)
a.peer = b; b.peer = a
del a, b
print("after del")
after delAnd that is all. Both objects are unreachable, yet __del__ was not called once. This is the only snippet the mechanism of this lesson cannot explain — the next lesson deals with it.Every object has a reference count. It sits in the header — those same first eight bytes from lesson 01.
The count goes up when a new reference appears and down when a reference disappears. References are created by: a name, a container element, an attribute of another object, a call argument, an intermediate value on the interpreter stack.
When the count reaches zero, the object is destroyed immediately. Not “at some point”, not “at the next collection” — right at that spot, synchronously.
Snippet A. While the function runs, the local variable r — more precisely, a frame slot — is looking at the object. When work returns, the frame is destroyed, all its slots release their references, the count of Res("A") drops to zero, and the destructor is called inside the return from the function — before the next line of the calling code runs.
Two conclusions follow at once. First: with in Python works not because someone carefully placed __exit__, but because the moment of an object's death is known exactly. Second, and more important: this is a property of the implementation, not of the language 🔧. The specification promises that an object will be destroyed and does not promise when. Snippet C is exactly about this: code that “always worked” starts accumulating open descriptors on another implementation. That is why with is not a matter of style.
Snippet B stops being a puzzle once you remember that a function argument is a reference too. The name x gives one, the parameter of getrefcount inside the call gives a second. Hence two. In the second case the parameter o of function f is added as well, hence three.
This is not a measurement curiosity but an exact description of how the mechanism works: every time an object is passed anywhere is an increment, every exit from a scope is a decrement. The count moves constantly, at the slightest provocation.
Here it is worth stopping and deriving it yourself. The count is an ordinary integer in memory. Two threads release references to one object at the same time. Both read the value 2, both subtract one, both write 1. One update is lost, the count will never reach zero — a leak. The symmetric case is worse: the count drops to zero too early, the object is destroyed out from under a live reference, and what follows is an access to freed memory.
List the options before reading on.
CPython chose the third. The GIL is not a separate decision and not a shortcoming. It is the price of deterministic destruction. And now it is clear why removing it is so hard: the reference count sticks out in the public C API, and thousands of extensions rely on the assumption “nobody touches me in parallel”.
Snippet D. a.peer = b and b.peer = a are two references living inside the objects themselves. After del a, b there are no external references left, but each object's count is one: its neighbour holds it. Zero is unreachable, and the memory is never freed.
A count is local by nature — it knows only “how many are looking at me” and not “am I reachable from anywhere outside”. So a second mechanism is needed, one that works with reachability rather than quantity. The next lesson is devoted to it.
All of this is about CPython 🔧. PyPy, GraalPy and Jython use tracing collection and have no count at all. Code that relies on the moment of destruction behaves differently there — and that is not considered their bug.
Some objects are immortal. Starting with 3.12, None, True, False, small integers and interned strings have a fixed count that does not move at all 🔧. This was done for free-threading: such objects no longer have a hot spot of contention. On 3.11 and earlier their counts are ordinary, so sys.getrefcount(None) shows something fundamentally different on different versions.
getrefcount must not be used for logic. It is always too high by at least one and depends on how many temporary references the interpreter holds at that moment. As a debugging tool it is fine; as a condition in code, never.
The decision: an object's lifetime is governed by a reference count. It was made at the very beginning, in 1990, and for reasons that looked indisputable at the time.
A count is simple: a hundred lines, no graph traversals, no pauses. It is predictable: the program does not freeze at a random moment. And, as turned out to matter most, it is transparent to C — an extension can own an object while knowing nothing about a collector: it incremented the count, used the object, decremented the count. That property is what made the whole scientific stack possible — and twenty years later it became the main reason the GIL cannot simply be deleted.
The price emerged gradually. First cycles turned up — a second mechanism was needed. Then multithreading — a global lock was needed. Neither was obvious in 1990, when multi-core machines did not exist for an ordinary developer.
This is std::shared_ptr, and here the analogy is not approximate but exact: a count in the object, an increment when an owner is copied, destruction when it reaches zero. Even the disease matches — cyclic references in C++ are not collected in just the same way, and are cured in just the same way: weak_ptr versus weakref.
If you have worked with PyTorch, you have a second familiar manifestation. Every tensor with requires_grad holds references to nodes of the computation graph, and those hold references to the input tensors. As long as a reference to loss is alive, the whole graph is alive all the way back to the input. This is not a quirk of the framework — it is exactly consequence 1 in action, and it explains the most common cause of OOM in a training loop.
Questions that come up on their own if you read closely. The answer is under the question.
Because in 1990 a count was the only way to get deterministic destruction for free, and Java was solving a different problem.
A count gives what a tracing collector cannot give in principle: an object dies at the moment it stops being looked at. Hence a with that works, hence the habit of writing open(path).read(), hence predictable memory in a long-lived process — it does not grow in a sawtooth between collections.
The price turned out to be huge, and it is still being paid:
Java chose the opposite: only a tracing collector, no determinism (finalize was declared unreliable and eventually removed), but multithreading without a global lock and a generational allocator in which allocating an object is a pointer bump. Determinism there is the job of try-with-resources — that is, the same solution as with, only mandatory.
The conclusion worth taking away: this is not “Python chose worse”. These are two different answers to the question “who is responsible for releasing a resource”. Python bet that the count would cope by itself; Java bet that the programmer would write the block explicitly. Thirty years on, Python has arrived at the same with, and the bet on the count is still hanging there in the form of the GIL.
sys.getrefcount always return one more?Because passing an argument is a reference too.
import sys
x = object()
print(sys.getrefcount(x)) # → 2
There are two references: the name x and the parameter inside getrefcount, which exists while the function runs. There is nothing specific to the function itself — every call behaves this way; it is just visible here.
Hence the practice: what matters is the change, not the absolute value.
import sys
data = []
before = sys.getrefcount(data)
holder = {"k": data}
print(sys.getrefcount(data) - before) # → 1 the dictionary added a reference
Careful with the interpretation. The numbers for small integers, short strings and None mean nothing — those objects are cached and the whole process is looking at them. Checking the count makes sense only for your own objects, and better done not with the count but with weakref: it answers the direct question “alive or not” and does not depend on the details of counting.
import weakref, gc
class T: pass
t = T(); r = weakref.ref(t)
del t; gc.collect()
print(r()) # → None the object really is deadIn your own code — no. In understanding someone else's — you must.
These two things are regularly mixed up. The rule for code is simple: if a resource matters, with should release it. A file, a socket, a database connection, a lock, a temporary directory. It is one line, it works on any implementation, and it documents intent.
# works on CPython, accumulates descriptors on PyPy
data = open("f.txt").read()
# works everywhere and reads better
with open("f.txt") as fh:
data = fh.read()
Why know about the count, then. Because half of all the Python code ever written relies on it, and you will have to read that code. When a service on PyPy dies with “too many open files” while the same code ran on CPython for years, the explanation is only here. When an object does not die after del because it ended up in a cycle or in someone's cache — the same.
This is precisely the case the Canon's hardness scale was introduced for. 🔧 means not “do not use” but “works, but is not a promise”. The difference shows exactly when the implementation or the version changes — that is, at the most inconvenient moment.
with that works, which is nonetheless a CPython detail and not a language guarantee. Hence also getrefcount being one too high: a call argument is just as much a reference. And hence the GIL: the count is not atomic, and of the three ways to fix that, a global lock was the cheapest and the only one compatible with the C extensions already written. What the mechanism cannot do is see cycles: a local count knows nothing about reachability, and that needs a second mechanism.
Java, Go and JavaScript chose tracing collection and do not pay for determinism. They have no global lock; threads run in parallel for real. But the moment of destruction is unknown, and so each of these languages had to invent a separate construct for releasing resources: try-with-resources in Java, defer in Go, using in C#. Python got the same guarantee for free, as a side effect of the count.
Swift is the most interesting case: it chose exactly the same solution, only it inserts the count operations at compile time. And it got exactly the same problem with cycles. Only it solved it differently: there is no second mechanism, and cycles are the responsibility of the programmer, who has to place weak and unowned by hand. Python preferred to pay extra with a collector rather than put this on a human.
Three languages, one fork, three different prices. No option is free.
A training loop accumulates metrics. The line looks harmless and kills the process on memory in the middle of an epoch.
losses = []
for batch in loader:
loss = model(batch)
loss.backward()
losses.append(loss) # ← right here
print(sum(losses) / len(losses))
Review sees: we collect losses and compute the mean. All logical. But loss is not a number but a tensor holding a reference to the computation graph, which in turn holds the activations of the whole batch. The count of each graph node will not reach zero while the list is alive. A thousand steps later there are a thousand graphs in memory.
The same effect without any ML — a chain of references between objects, of which only the last one sticks out:
| what we hold | memory retained |
|---|---|
| whole objects (each refers to the previous one) | 20.0 MB |
| only the values needed | 0.11 MB |
A difference of a hundred and eighty times, caused by one reference in each object. The cure is the same as in ML: store the value, not the object — losses.append(loss.item()). The general rule follows straight from the mechanism: if an object is put into a long-lived container, the whole graph reachable from it is retained with it. Put out the minimum.
“Memory is growing, and who holds the object is unclear.” Days go into this, although the mechanism answers in a minute.
The count knows how many references there are. The collector knows who holds them, and can show it:
import gc, sys
print(sys.getrefcount(model))
# → 3
for r in gc.get_referrers(model):
print(type(r).__name__, str(r)[:60])
# → dict {140234...: <__main__.Model object at 0x7f53...>}
# → dict {'__name__': '__main__', ...}
The very first holder is a dictionary keyed by id. That is someone's registry that nobody remembered to clean. What remains is to find who created that dictionary, and the question is closed.
A sequence of steps that works almost always: look at getrefcount and make sure there really are more holders than expected; get the list of them through get_referrers; if a holder is a container, repeat for it. For an aggregate picture of the whole process — tracemalloc with snapshots before and after, compared by lines of code.
A caveat: get_referrers sees only objects tracked by the collector, that is, containers. It will not show a reference from a C extension — and that is a diagnosis in itself, narrowing the search.
Run the four snippets and check them against your prediction. Then questions whose answers follow from the mechanism:
import sys
sys.getrefcount(None)
# Why is the number huge? And why is it different on 3.12?
def f():
x = SomeObject()
return 1 / 0
# Will x's destructor be called when the exception propagates? Why?
a = []
a.append(a)
del a
# What has just happened to the memory?
# And a question without code: why does collection on PyPy make
# free-threading an unnecessary problem?
The second question is the most practical one: the answer decides whether with is reliable under exceptions, and why exactly.
Lib/_weakrefset.py is a hundred lines implementing a set that does not retain its elements. In itself it is a simple wrapper, but what is interesting is why it is in the standard library.
Its main consumer is ABCMeta. When a class is registered as an implementation of an abstract base class, the registry has to remember it — and must not prevent it from being unloaded. An ordinary set would turn every registration into an eternal reference, and no such class would ever be collected. Look into Lib/abc.py and find _abc_registry: the mechanism of this lesson is visible there as a design constraint, not as theory.
Notice one more detail: WeakSet has a callback that is called when an element dies and cleans it out of the set. A weak reference does not merely “not hold” — it can report a death. That is what makes self-cleaning caches possible.
From L1 you know that every object has a count. Here: exactly where, and what it costs.
An object's header starts with the count field, and that is the first eight bytes at the object's address. So it can be read without any sys:
import ctypes
x = [1, 2, 3]; y = x
print(ctypes.c_ssize_t.from_address(id(x)).value)
# → 2
Two — x and y, with no inflation, because ctypes receives not the object itself but its address as a number. That is exactly why this method is more accurate than getrefcount for debugging.
In the sources the operations look like the macros Py_INCREF and Py_DECREF: an increment is one instruction; a decrement is an instruction plus a check for zero plus, at zero, a call to the type's destructor. Cheap one at a time and noticeable in total: the interpreter performs them every time an object is passed, including every intermediate value while evaluating expressions.
Hence a practical consequence that explains an old technique: hoisting self.method or obj.attr into a local variable before a hot loop pays off not only because of the attribute lookup (lesson 04) but also because an increment-decrement pair disappears from every iteration.
And hence the design of free-threading in 3.13: the count there is split into a local one for the owning thread and a shared one for everyone else, so that in the typical case — an object is used by the same thread that created it — the increment stays an ordinary non-atomic operation. Plus immortal objects, whose count does not move at all. Both measures exist precisely because consequence 2 makes the count the hottest spot in the interpreter.
Tag v3.11.15.
Include/object.h — the ob_refcnt field and the Py_INCREF / Py_DECREF macros. Twenty lines from which this whole lesson grows.Objects/object.c, _Py_Dealloc — what happens at the moment of reaching zero: a call to the type's tp_dealloc.Python/ceval_gil.h — the implementation of the GIL itself: a mutex, a condition variable, gil_drop_request and the switch interval. The file is small, and after consequence 3 it reads quite differently.weakref documentation — the write-up above is enough; go there when you need a callback on an object's death.