How Python works inside
CPython turns your code into bytecode and runs it in a loop. Every object carries a reference count, and it is freed as soon as that count drops to zero. Objects that point to each other in a cycle need the garbage collector. Freed memory often stays inside the process, so the process does not get smaller. A specialist uses these ideas to find memory leaks, cut memory use and explain strange behavior.
Author: bezzad
Contents
The problem: a worker that slowly eats memory
Our shop has a worker that syncs orders with the warehouse. It starts with 300 MB of memory. After one day it uses 2 GB, and the container is killed for “out of memory”. Then it starts again and the story repeats.
The team tried three things:
- They called gc.collect() every minute. Nothing changed.
- They deleted big lists with del. The memory graph stayed high.
- They said “Python has a garbage collector, so it cannot leak”. But it does.
To fix this, you must know how CPython runs code, when it frees an object, and where the memory goes after that.
From source code to bytecode
CPython is the normal Python interpreter (the one from python.org). It does not run your text directly:
- The compiler turns the source into bytecode: small instructions for a virtual machine.
- The bytecode is cached in a .pyc file inside
__pycache__, so the next import is faster. It is not faster to run, only faster to load. - The eval loop reads one instruction at a time and runs it.
- Since Python 3.11, the loop is “specializing”: after an instruction runs a few times with the same kind of data, CPython swaps it for a faster version, for example an addition only for two ints.
You can see the bytecode with the dis module:
import dis
def total(prices: list[float]) -> float:
s = 0.0
for p in prices:
s += p
return s
dis.dis(total) # LOAD_FAST, BINARY_OP (+=), FOR_ITER, ...
Why does a specialist care? Because it explains things like these:
- A local variable is faster than a global one. Locals are read by index (LOAD_FAST). Globals are looked up in a dict.
- Built-in functions like sum() are faster than a Python loop, because the loop runs in C, not in bytecode.
- Python 3.13 added an experimental JIT compiler. It is off by default. Do not expect it to fix slow code today.
Every object has a reference count
In CPython, every object has a small header with two things: its type and its reference count. The count says how many references point to the object: names, list items, dict values, attributes and so on.
- When you write cart = [order], the order gets one more reference.
- When a name goes away (del, the end of a function, a new value for the name), the count goes down.
- When the count reaches zero, the object is freed at once. No waiting, no pause.
import sys
order = {"id": 42, "total": 99.0}
cart = [order]
print(sys.getrefcount(order)) # 3: order, cart[0] and the call itself
del cart
print(sys.getrefcount(order)) # 2
This is why a file opened in a function is usually closed when the function ends. But do not depend on it. Use with, because other Python versions (like PyPy) do not use reference counting.
Two small facts that often come up in interviews:
- Small ints from -5 to 256 are cached. So a is b may be True for 100 and False for 1000. Never use is to compare values. Use ==. Use is only for None, True, False and your own sentinel objects.
- Some strings are interned (short names, identifiers), so they can also be the same object. This is an optimization, not a rule.
Cycles and the garbage collector
Reference counting cannot free a cycle: objects that point to each other.
class Customer:
def __init__(self, name: str):
self.name = name
self.orders: list["Order"] = []
class Order:
def __init__(self, customer: Customer):
self.customer = customer # order -> customer
customer.orders.append(self) # customer -> order
c = Customer("Sara")
Order(c)
del c # both objects still have a count of 1
For this, CPython has a cyclic garbage collector (the gc module):
- It runs from time to time, based on how many objects were created.
- It looks at container objects (lists, dicts, class instances) and finds groups that are only reachable from each other. It frees them.
- Objects are put into generations. Young objects are checked often, old ones rarely. Since Python 3.14, the collector works in small steps (incremental), so long pauses are shorter.
- gc.disable() only stops the cycle collector. Reference counting still frees normal objects.
The cycle collector works, but it costs time. Two ways to avoid cycles:
- Do not keep a back-link when you do not need it. Often the order only needs the customer id, not the customer object.
- Use a weak reference (weakref) for back-links and caches. A weak reference does not raise the count, so it does not keep the object alive.
Where does freed memory go?
When an object is freed, its memory usually does not go back to the operating system at once:
- CPython has its own allocator for small objects (pymalloc). It takes big blocks (arenas) from the OS and cuts them into small pieces.
- A freed piece goes back to CPython’s free list, ready for the next object.
- A whole arena goes back to the OS only when every object in it is freed. A few long-lived objects can keep an arena alive.
So “RSS stays high after del” is often not a leak. The memory is free for Python, but the OS still counts it. A real leak is when memory keeps growing while the work stays the same.
Finding a real leak
A leak in Python is almost always “something still has a reference”. The tracemalloc module shows which lines allocated the memory that is still alive:
import tracemalloc
tracemalloc.start()
before = tracemalloc.take_snapshot()
run_sync_batches(100) # the code we suspect
after = tracemalloc.take_snapshot()
for stat in after.compare_to(before, "lineno")[:5]:
print(stat) # file:line, size +12 MB, count +80000
The usual causes, from most common:
- A cache with no limit. A module-level dict that only grows. Give it a maximum size, a time limit, or use a real cache like Redis.
- lru_cache on a method. The cache lives on the class, and every key includes self. So every object that ever called the method stays alive forever, with everything it holds.
- Lists of callbacks or listeners that are added but never removed.
- Saved exceptions. An exception keeps its traceback, and the traceback keeps every frame with all its local variables.
- C extensions that leak in their own code. tracemalloc does not see memory allocated outside Python’s allocator.
Using less memory
When you hold millions of small objects, their size matters. Measure first, then pick one of these:
from dataclasses import dataclass
@dataclass(slots=True, frozen=True)
class PriceRow:
sku: str
price: float
currency: str
__slots__(or dataclass(slots=True)) gives the object fixed fields and no per-object__dict__. It saves memory and makes attribute access a little faster. You cannot add new attributes at runtime.- Tuples or named tuples are small and immutable.
- Columns instead of objects: the array module, NumPy or a dataframe store numbers as raw values, not as one Python object per number.
- Generators let you process rows one by one instead of loading all of them into a list.
Since Python 3.11 and 3.12, normal objects already use less memory than before, so the gain from __slots__ is smaller than old articles say. Always measure with tracemalloc or sys.getsizeof, and remember that getsizeof does not include the objects inside.
And the GIL?
In the normal build, the GIL protects the reference counts, so only one thread runs Python bytecode at a time. The free-threaded build (official since Python 3.14, still optional) removes the GIL and uses a different, thread-safe way to count references. The details are in the lesson “Concurrency in Python”.
Common mistakes
| Mistake | Result | Better way |
|---|---|---|
| Calling gc.collect() to fix a leak | Nothing changes, the reference is still there. | Find the reference with tracemalloc and remove it. |
| Using is to compare numbers or strings | Works for small values, fails for big ones. | Use ==. Use is only for None and sentinels. |
| A dict cache with no limit | Memory grows until the process is killed. | Set a max size or a time limit. |
| lru_cache on a method of short-lived objects | Every object stays alive forever. | Cache a plain function, or keep a cache per object. |
| Thinking high RSS after del is a leak | Time lost on a problem that is not there. | Check if memory keeps growing under the same load. |
| Millions of tiny objects | Several times more memory than the raw data. | Use slots, tuples, arrays, or process rows as a stream. |
Summary in 7 lines
- CPython compiles code to bytecode, caches it in .pyc files and runs it in an eval loop that specializes hot instructions.
- Every object has a reference count and is freed at once when the count reaches zero.
- Cycles need the cyclic garbage collector. Avoid them with ids or weak references.
- Freed memory usually stays in the process, so high RSS alone is not a leak.
- A leak means something still holds a reference: an unbounded cache, lru_cache on a method, listeners or saved tracebacks.
- Find it with tracemalloc snapshots, not with gc.collect().
- For millions of objects, use slots, tuples, arrays or streams, and measure first.