Names, objects and reference counts
Python memory questions come down to three ideas: names point to objects, reference counting frees most objects instantly, and a cycle collector handles the rest. Add profiling skills and you can answer most performance questions.
- ModelNames, objects, identity and mutability.
- MemoryReference counting, GC and leaks.
- InterpreterBytecode, implementations and speed.
For experienced roles, interviewers go under the hood: how Python stores objects, when memory is freed, why some code leaks, and what the interpreter actually runs. You do not need to know CPython's source — just a clear, correct model.
1. How do variables work in Python?
Variables are names bound to objects, not boxes holding values. Assignment binds a name to an object; several names can refer to the same object. Every object has an identity (id()), a type and a value. That model explains aliasing, mutability surprises and the behaviour of function arguments.
a = [1, 2]
b = a # same object, two names
print(a is b) # True
b = b + [3] # new object; a is unchanged
print(a, b) # [1, 2] [1, 2, 3]2. How does CPython free memory?
Mainly through reference counting: every object counts the references to it, and when the count drops to zero it is freed immediately. Reference counting cannot free cycles (objects referring to each other), so a cyclic garbage collector runs periodically over container objects, organised in generations so young objects are checked most often.
import sys, gc
data = []
print(sys.getrefcount(data)) # 2 (the name + the call argument)
class Node:
def __init__(self): self.other = None
a, b = Node(), Node()
a.other, b.other = b, a # a cycle
del a, b
print(gc.collect()) # the cycle collector frees them3. Why does a is b sometimes return True for equal numbers?
CPython pre-creates and reuses small integers (−5 to 256) and interns some strings, so equal values may share one object. Larger numbers created at runtime are separate objects. This is an optimisation detail — never use is to compare values; use it only for None, True, False and sentinel objects.
a, b = 256, 256
print(a is b) # True (cached)
x = int("1000")
y = int("1000")
print(x is y) # False — different objects
print(x == y) # True — always compare values with ==4. What causes memory leaks in Python?
Objects that stay reachable: ever-growing global lists or dicts used as caches, references held by long-lived objects (event listeners, class attributes), unbounded lru_cache on methods (it holds self), cycles with objects that wrap native resources, and C extensions. Investigate with tracemalloc or memory profilers and compare snapshots.
import tracemalloc
tracemalloc.start()
run_suspicious_job()
snapshot = tracemalloc.take_snapshot()
for stat in snapshot.statistics("lineno")[:5]:
print(stat) # top 5 lines by allocated memory5. What does __slots__ do and when is it worth it?
By default each instance stores attributes in a per-object __dict__. Declaring __slots__ replaces it with fixed slots, saving a lot of memory when you create millions of small objects and making attribute access slightly faster. The cost: you cannot add new attributes dynamically.
class Point:
__slots__ = ("x", "y")
def __init__(self, x, y):
self.x, self.y = x, y
p = Point(1, 2)
# p.z = 3 -> AttributeError: no slot for 'z'6. What actually runs when you execute a Python file?
CPython compiles the source to bytecode (cached in __pycache__ as .pyc files), then its virtual machine interprets that bytecode instruction by instruction. You can inspect it with the dis module. Python 3.11+ added a specialising adaptive interpreter that sped up typical code significantly, and 3.13 introduced an experimental JIT.
import dis
def add(a, b):
return a + b
dis.dis(add)
# LOAD_FAST a, LOAD_FAST b, BINARY_OP (+), RETURN_VALUE7. CPython, PyPy and others — what is the difference?
CPython is the reference implementation written in C, used almost everywhere. PyPy uses a JIT compiler and can run long-running pure-Python code several times faster, but has more limited support for C extensions. Cython compiles Python-like code to C extensions; MicroPython targets microcontrollers.
8. How do you make Python code faster?
First measure with cProfile or py-spy. Then: better algorithms and data structures (set instead of list lookups), built-ins and comprehensions instead of manual loops, vectorised NumPy/pandas operations, caching, avoiding repeated work inside loops, multiprocessing for CPU-bound tasks, and only then compiled extensions (Cython, Rust via PyO3).
python -m cProfile -s cumulative report.py | head -20Remember
Key points
- Refcount zero = freed
Cycles need the garbage collector.
- is compares identity
Small-int caching is an implementation detail.
- __slots__ saves memory
For millions of small objects.
- Profile before optimising
cProfile, py-spy and tracemalloc.
Interview drill
Follow-up questions
What the interviewer asks after your first answer. Turn on practice mode, answer each one aloud, then reveal.
-
1 What does del actually do? Basic
It removes a name binding (or an item from a container) and decrements the reference count. The object is freed only when no references remain.
-
2 What is a weak reference? Advanced
A reference from the
weakrefmodule that does not increase the reference count, so the object can still be freed — useful for caches and observer lists without leaks. -
3 Why is sys.getsizeof misleading for containers? Intermediate
It reports only the container's own memory, not the objects it references. Use a recursive measure or
tracemallocfor the real total. -
4 What is the free-threaded build of Python? Advanced
An optional CPython build (3.13+) without the Global Interpreter Lock, so threads can run Python code in parallel on several cores. It is still maturing; the standard build keeps the GIL.
-
5 How do you disable or tune the garbage collector? Advanced
gc.disable(),gc.set_threshold()andgc.freeze()exist for special cases (some web servers freeze objects after start-up). Most applications should leave it alone. -
6 What are .pyc files and can you delete them? Basic
Cached bytecode that speeds up imports. They are regenerated automatically, so deleting them is safe; keep
__pycache__out of Git.