今日已更新 147 条资讯 | 累计 32782 条内容
关于我们

How Python Takes Out Its Own Garbage

samconibear 2026年08月18日 02:28 1 次阅读 来源:Dev.to

Python manages memory automatically, freeing developers from manual allocation and deallocation. It does this through two complementary mechanisms: reference counting and a generational garbage collector for cyclic references. This article covers how garbage collection works in CPython. In other implementations such as PyPy, it works under a different mechanism Reference Counting: The Primary Mechanism Every object in Python carries a reference count, a tally of how many references point to it. This count increments when: A new reference is assigned ( y = x ) It's stored in a container (list, dict, etc.) The object is passed into a function It decrements when: A reference goes out of scope A reference is reassigned del is manually called on a reference import sys x = [] y = x z = { " y " : y } print ( sys . getrefcount ( x )) # 4 (x + y + z + the arg to getrefcount) y = 1 del z print ( sys . getrefcount ( x )) # 2 (x + the arg to getrefcount) When the count hits zero, CPython deallocates the object immediately . This is a key difference from garbage-collected languages like Java, JS or the PyPy implementation, where collection timing is unpredictable. The Problem: Reference Cycles Reference counting alone cannot handle cyclic references, where objects reference each other and keep their counts above zero even when unreachable from the program: class MyClass : def __init__ ( self ): self . ref = None a = MyClass () b = MyClass () a . ref = b b . ref = a del a del b # a and b still reference each other -> the refcount never reaches 0 This causes a memory leak. The Solution: Generational Garbage Collector To catch scenarios like the above, Python includes a separate cyclic garbage collector, implemented in the gc module. It's based on the generational hypothesis : most objects die young, so recently created objects are checked more frequently than long-lived ones. Objects are organized into three generations : Generation Description Collection Frequency 0 Newly created

本文内容来源于互联网,版权归原作者所有
查看原文