Python Glossary Русский

all Python 3gcfunction

gc.collect()

collection control

Runs the cyclic garbage collector right away and returns the number of unreachable objects found.

Syntax

gc.collect(generation=2)

CPython frees most objects by reference counting right after del, and they never need gc.collect: the collector only looks for cycles (an object referring to itself, or a pair referring to each other). The returned number is not 'memory freed' and differs between versions, so do not rely on it. Calling collect in a loop 'to save memory' is costly: a full walk over every container. The argument is a generation 0–2, otherwise ValueError.

Examples

import gc, weakref
class Node:
    pass
gc.disable()  # чтобы автоматическая сборка не вмешалась
n = Node()
n.me = n  # цикл: объект ссылается сам на себя
r = weakref.ref(n)
del n
print(r() is None)  # → False — подсчёт ссылок цикл не освободил
print(gc.collect() > 0, r() is None)  # → True True
gc.enable()
import gc
try:
    gc.collect(3)
except ValueError as e:
    print(e)  # → invalid generation

See also

Open in the full glossarydocs.python.orgReport an inaccuracy