Reputation:
I understand Python GC works in two ways:
1) Basic reference counting - below "John" has reference count of zero when "name" set to "Tom"
name = "John"
name = "Tom" (Reference count zero for "John")
2) Detect Circular References (Islands of Isolation). "GC" works at in-deterministic time (or if you invoke gc.collect() which isn't recommended).
Now, My question is, for (1), when name set to "Tom", "John" isn't collected immediately as soon as name = "Tom" right? GC would just mark "John" as un-reacheable and thus ready for collection (Which will happen later).
My understanding correct? Thanks
Reference:
https://rushter.com/blog/python-garbage-collector/
https://pythoninternal.wordpress.com/2014/08/04/the-garbage-collector/
Upvotes: 3
Views: 344
Reputation: 70592
Close, but the key detail is off: when a reference count falls to 0 in CPython, the then-unreferenced object is immediately collected. This has nothing to do with the cyclic GC system. Indeed, you can do gc.disable()
to disable the cyclic GC system completely, and reference counting will continue to collect non-cyclic garbage all on its own.
You can see this yourself via, e.g.,
import gc
gc.disable()
i = 1
while True:
xs = [i]
i += 1
That runs forever, but memory use will remain steady. That's because reference counting alone recycles the memory for the integer and the list created on each iteration.
Upvotes: 4