Exercises: Memory Management in Python
starter.py below, then run
python3 starter.py from inside the folder you saved it
in. Every task uses only the standard library — no installs
needed.
1 Reading a refcount
Write refcount_of(obj) — return sys.getrefcount(obj).
2 Building and collecting a reference cycle
Write make_cycle() — build two objects that reference each other, then return how many objects gc.collect() reports freeing.
3 Fixing a mutable default argument
Write add_item_safe(item, cart=None) — the safe version of the classic gotcha.
4 __slots__
Write class SlottedPoint with __slots__ = ("x", "y"), and point_instance_size(x, y).
5 Measuring one object's size
Write object_size(obj) — return sys.getsizeof(obj).
6 Peak memory of a list build
Write peak_memory_of_list_build(n) — measure a list comprehension of n squares with tracemalloc.
7 Peak memory of a generator build
Write peak_memory_of_generator_build(n) — the same, for the equivalent generator expression.
8 Comparing the two
Write is_generator_smaller(n) — compare the two peak-memory results.
🐞 Task 9 — Debug the Code
This is supposed to give every call its own fresh list when no log is passed in, but it reuses the same list across calls. Find and fix it.
def add_to_log(entry, log=[]):
log.append(entry)
return log
print(add_to_log("first"))
print(add_to_log("second"))