Reading preferences
Concept

References, Memory, and Garbage Collection

Follow references to a shared object and distinguish reachability from collection timing.

python, memory, references, garbage collection, lifecycle

Names refer to objects

Assignment binds a name to an object; it does not necessarily copy that object. Multiple references can point to one mutable object. Rebinding one name leaves the others unchanged.

Python illustration

a = [1]
b = a
a = None
b.append(2)
print(a, b)
del b

Prepared output — not live execution:

None [1, 2]

After b = a, both names refer to one list. Rebinding a to None does not change the list. The append changes the list through b. After del b, neither of these names refers to the list; this example keeps no other application reference to it.

See the reasoning

Follow the references

Arrows show which names refer to the list. This is a prepared example, not live Python execution.

Create a list

Names and list referencesa refers to the new list. b has not been bound yet.Name alistName bunboundList object[1]

a refers to the new list. b has not been bound yet.

Collection is not resource management

Python implementations may reclaim unreachable objects at different times. CPython commonly uses reference counting plus a cyclic garbage collector; an isolated cycle can require cyclic collection. Finalisation, weak references, interpreter shutdown, and extension objects make lifetimes more subtle than a count in a small diagram. A weak reference does not keep its referent alive; not every object type supports weak references.

Use with or explicit cleanup for files, locks, and connections instead of depending on garbage collection. gc.collect() requests a collection but is not a substitute for understanding retained references. Releasing an object does not guarantee the operating system immediately receives its memory.

Reflect on the concept

Four fixed questions to reinforce the reasoning. Answers are not saved or scored.

1. What happens when two names refer to the same mutable list and one mutates it?
2. Does rebinding one name remove other references to the original object?
3. Why does CPython have a cyclic garbage collector?
4. Should a program rely on prompt garbage collection to close a file?

References and further reading