Home β€Ί Curriculum β€Ί The GIL & Memory Management
Updated for Python 3.12+ Β· November 2026

🧠 The GIL & Memory Management
in Python

Learn how CPython manages memory: references, sys.getrefcount, garbage collection and cycles, weakref, __slots__, interning, mutable defaults, and what the GIL really does.

Advanced 9 lessonsβ‰ˆ 56 min read by Glenn Pansensoy

What this lesson is about

Python hides memory management so well that many people write Python for years without thinking about it. Then one day a list grows without bound, a function remembers an argument it should have forgotten, an object refuses to be freed, or someone tells you that Python threads cannot use multiple cores. Each of these questions has the same root: how CPython represents objects, counts references to them, and protects its own internals.

This lesson opens that box. We will look at names and objects, the reference count that decides when an object dies, the cyclic garbage collector that cleans up what counting cannot, and the weakref module for pointing at an object without keeping it alive. Then we look at practical memory tools (__slots__, interning, cheaper data structures), the mutable-default and shallow-copy traps, and finally the Global Interpreter Lock, explained honestly: what it is, why it exists, what it protects, and what it does not.

Everything here is runnable in your browser. I avoid printing raw reference counts, memory addresses and byte sizes, because those numbers change between Python versions and machines. Instead the examples print things that are stable: how a count *changed*, whether something is True or False, whether an object is still alive. That is also the right habit for reasoning about memory: think in relationships, not absolute numbers. This is an implementation-detail topic, so I will mark clearly which behaviours are language guarantees and which are only CPython's current behaviour.

What you will learn

  • βœ“Explain names, objects, aliasing and the difference between is and ==
  • βœ“Observe reference counting with sys.getrefcount, using relative changes
  • βœ“Build a reference cycle, watch the garbage collector reclaim it, and detect it with weakref
  • βœ“Use weak references and WeakValueDictionary for caches that do not leak
  • βœ“Reduce per-object memory with __slots__ and know its trade-offs
  • βœ“Understand interning and why is is the wrong way to compare values
  • βœ“Avoid the mutable default argument bug and the shallow-copy trap
  • βœ“Describe what the GIL protects, what it does not, and when threads still help

Why programmers should learn this

  • β˜…Understanding references explains most surprising Python behaviour: why changing one list changes another, why a default argument keeps its value between calls, and why copy is sometimes not enough.
  • β˜…Memory leaks in long-running programs such as web servers and bots usually come from objects kept alive by a forgotten reference, a cache or a cycle; knowing the model tells you where to look.
  • β˜…Using __slots__ or generators in the right place can cut memory use for programs that create millions of small objects, without changing the design.
  • β˜…Interview questions about the GIL, garbage collection and is versus == come up often, and a precise answer shows real understanding rather than memorised slogans.
  • β˜…Knowing exactly what the GIL protects helps you decide between threads, processes and async, and write thread-safe code instead of hoping the GIL will save you.

Names, objects and aliasing

In Python a variable is not a box that holds a value. It is a name that points to an object living elsewhere. The assignment b = a does not copy anything: it makes a second name point to the same object. For immutable objects such as numbers, strings and tuples this never causes trouble, because the object cannot change. For mutable objects such as lists, dictionaries and sets, both names see every change, and that is what people call aliasing.

The operator is asks whether two names point to the same object; == asks whether the two objects have equal values. Two separate lists with the same contents are equal but not identical. In everyday code you almost always want ==. The one standard use of is is comparing with singletons like None, as in if x is None.

Try the example and notice that I never print an object's address. What matters is the relationship: which names share an object and which do not. Changing the object through one name changes what the other name sees, because there is only one object.

python
a = [1, 2, 3]
b = a
c = [1, 2, 3]

print(a == c, a is c)
print(a is b)

b.append(4)
print(a)
print(c)

def add_item(items, value):
    items.append(value)

add_item(a, 5)
print(a, b)

x = None
print(x is None)
Expected output
True False
True
[1, 2, 3, 4]
[1, 2, 3]
[1, 2, 3, 4, 5] [1, 2, 3, 4, 5]
True

Line by line

  1. 1-3b is another name for the same list as a. c is a brand new list that happens to hold the same values.
  2. 5-6a == c is True (equal contents) but a is c is False (different objects). a is b is True.
  3. 8-10Appending through b changes the one shared list, so a shows 4. c is a different object and is untouched.
  4. 12-15Passing a list to a function passes a reference, so the function's append changes the caller's list. Python passes object references by value, so rebinding the parameter would not change the caller, but mutating the object does.
  5. 17-18is None is the idiomatic singleton test.
πŸ’‘

If you are unsure whether two names share an object, mutate one and look at the other. For lists, copy() or list(a) makes a new top-level list.

Reference counting with sys.getrefcount

CPython keeps a counter inside every object: the reference count, the number of references currently pointing at it. When you bind a new name, put the object in a list or pass it to a function, the count goes up. When a name is deleted, rebinds, or goes out of scope, it goes down. When it reaches zero the object is freed immediately, which is why files and locks held by a temporary object are often released the moment the last reference vanishes.

sys.getrefcount(obj) shows the count, but with a catch: the call itself adds a temporary reference for its argument, so the number is one higher than you expect, and the base value also depends on the Python version and on interpreter internals. For that reason I never print the raw number. I record a baseline and print how much it *changed*. That difference is stable on every machine.

You can also use weakref to observe death. A weak reference does not keep its target alive, and calling it returns the object while it lives and None after it is freed. In the second block I define a class whose objects can be weakly referenced, delete the only name, and the weak reference immediately reads None. That is reference counting at work.

Counting references
import sys

data = []
base = sys.getrefcount(data)

alias = data
print("after alias:", sys.getrefcount(data) - base)

holder = [data]
print("after list holds it:", sys.getrefcount(data) - base)

del alias
print("after del alias:", sys.getrefcount(data) - base)

holder.clear()
print("after clearing list:", sys.getrefcount(data) - base)
Expected output
after alias: 1
after list holds it: 2
after del alias: 1
after clearing list: 0

Line by line

  1. 3-4Create a list and record the baseline count. Whatever its absolute value, we only care about changes.
  2. 6-7A second name adds one reference.
  3. 9-10Storing the list inside another list adds a second extra reference.
  4. 12-13Deleting a name removes one reference.
  5. 15-16Clearing the holder list removes the last extra reference, so the difference returns to zero.
Watching an object die
import weakref

class Resource:
    pass

r = Resource()
probe = weakref.ref(r)
print("alive:", probe() is not None)

other = r
del r
print("still alive after one del:", probe() is not None)

del other
print("alive after last name removed:", probe() is not None)
Expected output
alive: True
still alive after one del: True
alive after last name removed: False

Line by line

  1. 3-4A plain class; instances support weak references by default.
  2. 6-8Create an object and a weak reference to it. Calling probe() returns the object while it exists.
  3. 10-12Two names point at the object. Deleting one leaves a name behind, so the count is still above zero and the object lives.
  4. 14-15Deleting the last name drops the count to zero, CPython frees the object at once, and the weak reference now returns None.
ℹ️

Reference counting is how CPython works today, not a promise of the language. Other implementations such as PyPy use different strategies, so never rely on an object being freed at an exact moment; use with blocks for resources that must be released.

Cycles and the garbage collector

Reference counting has one weakness: cycles. If object A holds a reference to B and B holds one back to A, then deleting every outside name still leaves each with a count of one. Neither reaches zero, so counting alone would leak them forever. Python solves this with a second system, the cyclic garbage collector in the gc module. It periodically searches container objects for groups that are only reachable from each other and frees them.

The collector runs automatically based on allocation counts, but you can also call gc.collect() yourself. In the example I switch automatic collection off so the demonstration is fully predictable (and switch it back on at the end). I create two nodes that point at each other, delete my names, and use weak references to check whether they survive. They do, because the cycle keeps them alive, until gc.collect() runs.

This matters in practice for parent and child objects: a tree node that stores its parent and its children forms a cycle, as do observers that store callbacks to their owners. They are not catastrophic, since the collector eventually frees them, but they delay cleanup and make memory use less predictable. When a child needs to point back to its parent, a weak reference is the clean answer, as the last part of the example shows.

python
import gc
import weakref

class Node:
    def __init__(self, name):
        self.name = name
        self.partner = None

gc.disable()

a = Node("a")
b = Node("b")
a.partner = b
b.partner = a
probe_a = weakref.ref(a)
probe_b = weakref.ref(b)

del a, b
print("after del, a alive:", probe_a() is not None)
print("after del, b alive:", probe_b() is not None)

gc.collect()
print("after collect, a alive:", probe_a() is not None)
print("after collect, b alive:", probe_b() is not None)

parent = Node("parent")
child = Node("child")
child.partner = weakref.ref(parent)
print("child sees parent:", child.partner().name)
probe_p = weakref.ref(parent)
del parent
print("parent freed without gc:", probe_p() is None)

gc.enable()
Expected output
after del, a alive: True
after del, b alive: True
after collect, a alive: False
after collect, b alive: False
child sees parent: parent
parent freed without gc: True

Line by line

  1. 1-2gc is the garbage collector interface, weakref lets us observe objects without keeping them alive.
  2. 4-7A tiny class with a link to another node.
  3. 9Turn automatic collection off so nothing is freed behind our back during the demonstration.
  4. 11-16Create two nodes that reference each other, and attach weak references so we can check on them later.
  5. 18-20Remove our names. Because each node still references the other, neither count reaches zero: both are alive.
  6. 22-24gc.collect() finds the unreachable cycle and frees it, so both weak references now return None.
  7. 26-32The alternative: the child stores a *weak* reference to its parent. No cycle exists, so deleting the only strong name frees the parent immediately, with no collector needed.
  8. 34Restore the default behaviour.
πŸ’‘

Call gc.collect() in production code only when you have a reason, such as after releasing a huge structure. For everyday use, let the automatic collector do its job.

Weak references for caches

A cache that stores big objects forever is a memory leak with good intentions. If the cache should hold an object only while *somebody else* is using it, use weakref.WeakValueDictionary. It looks like a normal dictionary, but its values are weak references, so an entry disappears automatically when the last outside reference to its value goes away. A WeakKeyDictionary does the same with keys, which is useful for attaching extra data to objects you do not own.

There are limits. Weak references only work on objects that support them: instances of ordinary classes do, but built-in int, str, list, dict and tuple instances do not. A class that uses __slots__ must include __weakref__ in the slots to allow weak references. Weak caches also make behaviour depend on when objects die, so I use them for convenience caches where a miss is fine, not for anything where a missing entry would be a bug.

The example builds an image-like cache. While a caller holds the object it is found in the cache. Once the caller lets go, the entry vanishes by itself. I call gc.collect() before checking, only to make the demonstration independent of any cycles.

python
import gc
import weakref

class Image:
    def __init__(self, name):
        self.name = name

cache = weakref.WeakValueDictionary()

def load(name):
    img = cache.get(name)
    if img is None:
        img = Image(name)
        cache[name] = img
    return img

first = load("logo")
second = load("logo")
print("same object reused:", first is second)
print("entries while in use:", sorted(cache.keys()))

del first, second
gc.collect()
print("entries after release:", sorted(cache.keys()))

try:
    weakref.ref([1, 2, 3])
except TypeError as exc:
    print("lists cannot be weakly referenced")
Expected output
same object reused: True
entries while in use: ['logo']
entries after release: []
lists cannot be weakly referenced

Line by line

  1. 4-6A normal class, which supports weak references.
  2. 8A dictionary whose values are held weakly.
  3. 10-15A loader that reuses a cached image if one is alive, and otherwise creates and stores a new one.
  4. 17-19Two calls return the very same object, so the cache saved a load.
  5. 21-23With no strong references left, the image is freed and its cache entry disappears on its own.
  6. 25-28Built-in containers such as list reject weak references with TypeError.

__slots__: smaller objects

By default each instance of a normal class stores its attributes in a per-instance dictionary, __dict__. That is flexible (you can add any attribute at any time) but costs memory, which adds up when you create hundreds of thousands of small objects such as points, records or graph nodes. Declaring __slots__ = ("x", "y") tells Python to reserve fixed space for exactly those attributes and not to create a __dict__ at all.

The trade-offs are real. You can no longer add attributes that are not in the slots, a slotted class cannot be weakly referenced unless __weakref__ is listed, and multiple inheritance with several slotted bases can conflict. Dataclasses can generate slots for you (@dataclass(slots=True)), which pairs well with the dataclasses lesson. I reach for slots only after I know a program creates enough instances that memory matters, never by default.

I deliberately print comparisons instead of byte sizes, because sys.getsizeof figures differ between Python versions. The question that matters is stable: does the slotted object avoid the dictionary, and does it use less memory than the object plus its dictionary?

python
import sys

class PointDict:
    def __init__(self, x, y):
        self.x = x
        self.y = y

class PointSlots:
    __slots__ = ("x", "y")
    def __init__(self, x, y):
        self.x = x
        self.y = y

d = PointDict(1, 2)
s = PointSlots(1, 2)

print("normal has __dict__:", hasattr(d, "__dict__"))
print("slots has __dict__:", hasattr(s, "__dict__"))

d.color = "red"
print("normal accepts new attribute:", d.color)

try:
    s.color = "red"
except AttributeError:
    print("slots rejects new attribute")

normal_total = sys.getsizeof(d) + sys.getsizeof(d.__dict__)
print("slots object smaller than object + dict:", sys.getsizeof(s) < normal_total)
Expected output
normal has __dict__: True
slots has __dict__: False
normal accepts new attribute: red
slots rejects new attribute
slots object smaller than object + dict: True

Line by line

  1. 3-6An ordinary class: attributes live in a dictionary created for each instance.
  2. 8-12The same class with __slots__. The listed names get fixed storage, and no __dict__ exists.
  3. 14-15Create one of each.
  4. 17-18Only the normal object has a __dict__.
  5. 20-21A normal object accepts new attributes freely.
  6. 23-26A slotted object raises AttributeError for a name that is not in __slots__.
  7. 28-29Compare memory by the stable question: is the slotted instance smaller than the normal instance plus its dictionary? Yes.
⚠️

Slots save memory, not time you will notice in most programs. Measure with tracemalloc on your real data before changing a design for them.

Interning, identity and why not to use is

To save memory and speed up comparisons, CPython interns some objects: it keeps one shared copy and reuses it. Small integers from -5 to 256 are pre-created singletons, and short identifier-like string literals in your source are typically interned too. So a = 256; b = 256 gives a is b as True, while larger numbers computed at runtime usually produce separate objects.

That is exactly why is is the wrong tool for comparing values. The results depend on implementation details: how the number was produced, whether two literals were compiled together, even the Python version. Code that happens to work with is today can silently break tomorrow. Compare values with ==, and keep is for None, True, False and genuine identity checks.

There is one legitimate use of interning in your own code. If you store millions of repeated strings (for example the same category names parsed from a big file) and compare them often, sys.intern(text) gives every equal string the same object, which saves memory and makes equality checks fast. The example shows both the surprising integers and an intentional intern. I build the numbers with int(...) at run time so the result does not depend on how the compiler folds constants.

python
import sys

small_a = int("200")
small_b = int("200")
big_a = int("100000")
big_b = int("100000")

print("small ints shared:", small_a is small_b)
print("big ints shared:", big_a is big_b)
print("both equal:", small_a == small_b, big_a == big_b)

left = "".join(["ca", "ts"])
right = "".join(["ca", "ts"])
print("built at runtime, equal:", left == right)
print("built at runtime, identical:", left is right)

left_i = sys.intern(left)
right_i = sys.intern(right)
print("after sys.intern, identical:", left_i is right_i)
Expected output
small ints shared: True
big ints shared: False
both equal: True True
built at runtime, equal: True
built at runtime, identical: False
after sys.intern, identical: True

Line by line

  1. 3-6Create small and large integers at run time, so each assignment really makes a new value.
  2. 8-9CPython reuses the preallocated small integers, so those share one object, while large ones are separate. This is an implementation detail.
  3. 10Whatever is says, == is True for both pairs. == is the comparison that is safe to rely on.
  4. 12-15Two equal strings built separately are equal but not the same object.
  5. 17-19sys.intern returns one canonical object for equal strings, so the two interned results are identical.
⚠️

Never write if x is 5 or if name is "admin". Modern Python even raises a SyntaxWarning for is with a literal. Use ==.

Mutable defaults and shallow copies

Two memory-related traps catch almost every Python learner. The first is the mutable default argument. Default values are evaluated once, when the def statement runs, not each time the function is called. If the default is a list, every call that omits the argument shares that single list, and items added in one call show up in the next. The standard fix is to use None as the default and create a fresh list inside the function.

The second is the shallow copy. list.copy(), dict.copy() and the copy.copy() function create a new outer container but keep pointing at the same inner objects. For a list of numbers that is fine. For a list of lists, changing an inner list through the copy changes the original, because both outer lists hold the same inner list. copy.deepcopy recursively copies everything, at the price of time and memory.

The pattern behind both traps is the one from the first section: names point to objects, and mutation is visible to everyone who holds the object. Whenever a surprising change appears somewhere you did not expect, ask yourself which object two names are secretly sharing.

python
import copy

def buggy(item, bucket=[]):
    bucket.append(item)
    return bucket

print(buggy(1))
print(buggy(2))

def fixed(item, bucket=None):
    if bucket is None:
        bucket = []
    bucket.append(item)
    return bucket

print(fixed(1))
print(fixed(2))

grid = [[0, 0], [0, 0]]
shallow = grid.copy()
deep = copy.deepcopy(grid)
shallow[0][0] = 9
print("original after shallow edit:", grid)
print("deep copy unaffected:", deep)

rows = [[0] * 2] * 2
rows[0][0] = 1
print("repeated rows share one list:", rows)
Expected output
[1]
[1, 2]
[1]
[2]
original after shallow edit: [[9, 0], [0, 0]]
deep copy unaffected: [[0, 0], [0, 0]]
repeated rows share one list: [[1, 0], [1, 0]]

Line by line

  1. 3-5The default list is created once, when the function is defined, and then reused.
  2. 7-8The second call sees the first call's item: [1, 2].
  3. 10-14The fix: None as a sentinel, with a new list made inside the body on each call.
  4. 16-17Now each call without a bucket starts fresh.
  5. 19-24A shallow copy of a nested list still shares the inner lists, so editing through shallow changes grid. The deep copy is fully independent.
  6. 26-28[[0] * 2] * 2 repeats a reference to one inner list. Build rows with a comprehension, [[0] * 2 for _ in range(2)], instead.

The GIL, explained honestly

The Global Interpreter Lock is a mutex inside CPython that allows only one thread to execute Python bytecode at a time. It exists mainly because of reference counting: every object has a counter that is updated constantly, and making each of those updates individually thread-safe would be slow and complicated. One big lock is simpler and keeps single-threaded programs fast. It also made writing C extensions easier for many years.

The consequences are often described wrongly, so let me be precise. First, the GIL does not stop Python threads from working: a thread that waits for the network, a disk or time.sleep releases the lock, and many C libraries (NumPy, compression, hashing) release it while they do heavy work. So threads help I/O-bound work and some compiled work. Second, the GIL makes a *single* bytecode instruction safe, but your statements consist of many instructions, so counter += 1 is still a race condition, as the threading lesson demonstrates. The GIL is not a substitute for locks. Third, the interpreter switches threads on a timer, not at the end of statements, which is why an interleaving can happen almost anywhere between instructions.

To make the point visible, the example below disassembles a function that does n += 1 and shows it is several instructions, then prints the switch interval. I print only stable facts, not the instruction listing itself, because opcode names change between versions. Python 3.13 added an optional free-threaded build without the GIL, and 3.14 supports it as an optional build; the default build still has the GIL. Check your own version's documentation before depending on that.

python
import dis
import sys

def bump(n):
    n += 1
    return n

ops = [ins.opname for ins in dis.get_instructions(bump)]
print("instructions in bump:", len(ops) > 3)
print("has a separate add step:", "BINARY_OP" in ops)

print("switch interval in seconds:", sys.getswitchinterval())

def count_up(limit):
    total = 0
    for i in range(limit):
        total += i
    return total

print(count_up(1000))
Expected output
instructions in bump: True
has a separate add step: True
switch interval in seconds: 0.005
499500

Line by line

  1. 1-2dis shows the bytecode the interpreter runs for a function.
  2. 4-6A tiny function whose body is n += 1.
  3. 8-10Collect the instruction names. One innocent line becomes several steps: load, add, store. A thread switch can land between them. Printing a boolean keeps output stable across versions.
  4. 12The default thread switch interval is 5 milliseconds: after that long, a running thread is asked to give up the GIL.
  5. 14-19A plain computational loop: with the GIL, running this in two threads at once would not finish faster than running it twice in a row.
ℹ️

Rule of thumb: the GIL protects the interpreter's internals, not your program's logic. You still need locks, queues or immutable data for correct threaded code.

Practical ways to use less memory

Once you know how objects live, the memory-saving habits become obvious. Process data lazily with generators instead of building huge lists: a generator produces one item at a time and holds almost nothing. Use range rather than a list of numbers, because range stores only its start, stop and step. Use tuples for fixed records and __slots__ or @dataclass(slots=True) for many small objects. For large arrays of numbers, the array module or NumPy stores raw values contiguously instead of one Python object per number.

When you suspect a leak, look for things that keep references: module-level lists and dictionaries that only ever grow, caches without a size limit, closures and callbacks that capture big objects, and exceptions whose tracebacks hold on to frames. The standard library's tracemalloc module can tell you which lines allocated the most memory, and gc.get_referrers can show who is holding an object.

The example compares approaches with True/False statements so that the lesson holds on any version of Python.

python
import sys
from array import array

squares_list = [n * n for n in range(10_000)]
squares_gen = (n * n for n in range(10_000))
print("generator far smaller than list:", sys.getsizeof(squares_gen) < sys.getsizeof(squares_list))

print("range smaller than list:", sys.getsizeof(range(10_000)) < sys.getsizeof(list(range(10_000))))

print("sum from generator:", sum(n * n for n in range(10)))

packed = array("i", range(1000))
print("array typecode and length:", packed.typecode, len(packed))
print("array stores raw ints:", packed.itemsize == 4)

record = ("ada", 36)
name, age = record
print(name, age)
Expected output
generator far smaller than list: True
range smaller than list: True
sum from generator: 285
array typecode and length: i 1000
array stores raw ints: True
ada 36

Line by line

  1. 4-6A list comprehension builds all 10,000 values at once; the generator expression builds none until asked. The generator object is tiny however many items it will produce.
  2. 8range is a recipe (start, stop, step), not a stored sequence.
  3. 10Feed a generator straight into sum and no big list ever exists.
  4. 12-14array('i', ...) stores raw 32-bit integers side by side rather than one Python object per number, so it is compact.
  5. 16-18A tuple is an immutable, compact record that unpacks neatly.

Common mistakes

❌ Comparing values with is

is tests object identity, and CPython's integer and string caching makes it appear to work for small values. Use == for values and keep is for None and true identity checks.

❌ Using a mutable object as a default argument

def f(x, items=[]) creates the list once and shares it between calls. Use items=None and build the list inside the function.

❌ Thinking copy() copies everything

A shallow copy duplicates only the outer container. Nested lists and dictionaries are still shared. Use copy.deepcopy or rebuild the structure when you need independence.

❌ Believing the GIL makes threaded code safe

The GIL keeps interpreter internals consistent, but compound operations such as counter += 1 can still interleave. Protect shared mutable data with locks or queues.

❌ Letting caches and module-level lists grow forever

A global list, dict or memoisation cache keeps every entry alive. Bound it (for example with functools.lru_cache(maxsize=...)), clear it, or use weak references when entries should expire with their objects.

Quick quiz

Tap an answer. I explain every one, right or wrong.

Q1. After b = a where a is a list, what is true?

Q2. Why does sys.getrefcount(x) report a value one higher than the number of names you created?

Q3. Two objects reference each other and you delete all outside names. What frees them?

Q4. What does __slots__ do to instances of a class?

Q5. What happens with def f(x, items=[]): items.append(x); return items called twice as f(1) then f(2)?

Q6. Which statement about the GIL is accurate?

Frequently asked questions

No. CPython frees objects automatically through reference counting plus a cycle collector. What you do control is which references you keep: remove entries from long-lived containers, close files with with, and avoid unbounded caches.

del x removes the name x, which lowers the object's reference count by one. The object is freed only when no references remain, and even then the memory may be reused by Python rather than returned to the operating system at once.

CPython's allocator often keeps freed memory for reuse, and fragmentation can stop whole blocks from being returned. The objects are gone, so memory is available to your program again, even if the process size reported by the operating system stays high.

There is an optional free-threaded build, introduced as experimental in Python 3.13 and supported as optional from 3.14. The standard build still has the GIL. Check the documentation for your version and test your dependencies before relying on it. See threads and processes for what to use today.

When your program creates very many instances of a small class and profiling shows memory is a problem. For a handful of objects the saving is not worth the loss of flexibility. If you already use dataclasses, slots=True is the easiest way.

Key takeaways

  • βœ“A Python name points to an object; assignment shares the object rather than copying it, and is tests identity while == tests value.
  • βœ“CPython frees most objects the moment their reference count reaches zero, and the gc module handles reference cycles.
  • βœ“weakref lets you observe or cache objects without keeping them alive, and breaks parent-child cycles.
  • βœ“__slots__ removes the per-instance dictionary to save memory, at the cost of flexibility.
  • βœ“Never use is for value comparison, never use mutable default arguments, and remember that shallow copies share inner objects.
  • βœ“The GIL protects the interpreter, not your logic: threads help I/O-bound work, and shared data still needs locks or queues.