Fundamentals 4 min read

Practical Python Garbage Collection and Memory Analysis: 10 Useful Code Examples

This article presents ten practical Python code examples demonstrating various garbage collection mechanisms and memory‑analysis tools, including reference counting, cyclic references, object inspection, tracemalloc, memory_profiler, pympler, and objgraph, to help developers understand and optimize memory usage.

Test Development Learning Exchange
Test Development Learning Exchange
Test Development Learning Exchange
Practical Python Garbage Collection and Memory Analysis: 10 Useful Code Examples

In Python, garbage collection automatically manages memory by detecting objects that are no longer in use and freeing their memory, while memory analysis tools help identify leaks and optimize usage.

1. Reference counting garbage collection:

import sys

a = [1, 2, 3]
b = a
del a
print(sys.getrefcount(b))  # 输出: 2

2. Cyclic references and mark‑sweep garbage collection:

import gc

class Node:
    def __init__(self):
        self.next = None

a = Node()
b = Node()
a.next = b
b.next = a

# 手动触发垃圾回收
gc.collect()

3. Inspect an object's reference count:

import sys

a = [1, 2, 3]
print(sys.getrefcount(a))  # 输出: 2

4. Use gc.get_objects() to view currently existing objects:

import gc

objects = gc.get_objects()
print(len(objects))  # 输出: 当前存在的对象数量

5. Use gc.get_referents() to see an object's referents:

import gc

a = [1, 2, 3]
b = a
referents = gc.get_referents(b)
print(referents)  # 输出: [1, 2, 3]

6. Use gc.get_referrers() to see an object's referrers:

import gc

a = [1, 2, 3]
b = a
referrers = gc.get_referrers(a)
print(referrers)  # 输出: [b, globals()]

7. Use tracemalloc for memory profiling:

import tracemalloc

tracemalloc.start()
# 执行一些代码
snapshot = tracemalloc.take_snapshot()
top_stats = snapshot.statistics("lineno")

for stat in top_stats[:10]:
    print(stat)

8. Use memory_profiler for line‑by‑line memory analysis:

from memory_profiler import profile

@profile
def my_function():
    # 函数代码
    pass

my_function()

9. Use pympler.muppy() to list all current objects:

from pympler import muppy, summary

all_objects = muppy.get_objects()
sum1 = summary.summarize(all_objects)

summary.print_(sum1)

10. Use objgraph to generate an object reference graph:

import objgraph

a = [1, 2, 3]
b = [4, 5, 6]
a.append(b)
b.append(a)

objgraph.show_refs([a], filename="ref_graph.png")

These examples illustrate common scenarios for Python garbage collection and memory analysis, showing how to inspect reference counts, detect cyclic references, list existing objects, and employ tools such as tracemalloc , memory_profiler , pympler , and objgraph to understand and optimize memory usage.

Hope these examples are helpful; feel free to ask further questions.

debuggingMemory ManagementPythonGarbage CollectionMemory Profiling
Test Development Learning Exchange
Written by

Test Development Learning Exchange

Test Development Learning Exchange

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.