How Does Python Manage Memory? Understanding Objects, References, and GC
This article explains Python's memory management by exploring how objects are stored, how references and reference counting work, the role of the garbage collector, generational collection, and how reference cycles are detected and reclaimed.
Memory management is a key aspect of language design, directly affecting performance. Python, as a dynamic, object‑oriented language, separates objects from references and uses reference counting together with a generational garbage collector to reclaim memory.
Object Memory Usage
Assignment creates a reference to an object; the object itself (e.g., the integer 1) lives separately. Python caches small integers and short strings, so multiple references to the same value point to the same object. The built‑in id() function returns the object's memory address.
a = 1
print(id(a))
print(hex(id(a)))Running the code shows identical decimal and hexadecimal addresses for the same object.
Object References
Container objects (lists, dicts, etc.) store references to their elements, not the elements themselves. Custom objects can also hold references to other objects.
class FromObj(object):
def __init__(self, to_obj):
self.to_obj = to_obj
b = [1, 2, 3]
a = FromObj(b)
print(id(a.to_obj))
print(id(b))Both a.to_obj and b refer to the same list object.
Every object has a reference count. The sys.getrefcount() function reports it, noting that passing the object as an argument adds a temporary reference.
from sys import getrefcount
a = [1, 2, 3]
print(getrefcount(a))
b = a
print(getrefcount(b))Reference Reduction
The del statement removes a reference, decreasing the reference count. Reassigning a name also reduces the count of the previous object.
from sys import getrefcount
a = [1, 2, 3]
b = a
print(getrefcount(b))
del a
print(getrefcount(b))Deleting an element from a list similarly reduces its reference count.
a = [1, 2, 3]
del a[0]
print(a)Garbage Collection
When an object's reference count drops to zero, it becomes garbage and can be reclaimed. Python triggers garbage collection only when the difference between allocated and deallocated objects exceeds a threshold.
import gc
print(gc.get_threshold()) # e.g., (700, 10, 10)The thresholds can be inspected and modified with gc.set_threshold(). Manual collection is possible via gc.collect().
Generation Collection
Python groups objects into three generations (0, 1, 2). New objects start in generation 0; surviving objects are promoted to higher generations. Collection always scans generation 0, and after a certain number of passes also scans generations 1 and 2, as indicated by the second and third values of gc.get_threshold(). The thresholds can be tuned:
import gc
gc.set_threshold(700, 10, 5)Isolated Reference Cycles
Reference cycles (e.g., two lists referencing each other) keep objects alive even when their external references are removed, because their reference counts never reach zero. Python's cyclic GC breaks such cycles by traversing objects, adjusting temporary counts ( gc_ref), and reclaiming objects whose adjusted count becomes zero.
a = []
b = [a]
a.append(b)
# create a cycleSummary
Python separates objects from references and relies on reference counting for most memory reclamation. To handle reference cycles, it adds a generational garbage collector. Understanding these mechanisms is essential for writing efficient Python code.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
MaGe Linux Operations
Founded in 2009, MaGe Education is a top Chinese high‑end IT training brand. Its graduates earn 12K+ RMB salaries, and the school has trained tens of thousands of students. It offers high‑pay courses in Linux cloud operations, Python full‑stack, automation, data analysis, AI, and Go high‑concurrency architecture. Thanks to quality courses and a solid reputation, it has talent partnerships with numerous internet firms.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
