Garbage Collector and gc module
garbage-collection, python
Solution
In CPython, objects are cleared from memory immediately when their reference count drops to 0.
The moment you rebind `a` to `'hello'`, the reference count for the `'hi'` string object is decremented. If it reaches 0, it'll be removed from memory.
As such, the garbage collector only needs to deal with objects that (indirectly or directly) reference one another, and thus keep the reference count from ever dropping to 0.
Strings cannot reference other objects, so are not of interest to the garbage collector. But anything that can reference something else (such as containers types such as lists or dictionaries, or any Python class or instance) can produce a circular reference:
a = [] # Ref count is 1
a.append(a) # A circular reference! Ref count is now 2
del a # Ref count is decremented to 1
The garbage collector detects these circular references; nothing else references `a`, so eventually the gc process breaks the circle, letting the reference counts drop to 0 naturally.
Incidentally, the Python compiler bundles string literals such as `'hi'` and `'hello'` as constants with the bytecode produced and as such, there is always at least one reference to such objects. In addition, string literals used in source code that match the regular expression `[a-zA-Z0-9_]` are interned; made into singletons to reduce the memory footprint, so other code blocks that use the same string literal will hold a reference to the same shared string.
Problem
I was reading the documentation when I came in doubt with the following phrase: Since the collector supplements the reference counting already used in Python, you can disable the collector if you are sure your program does not create reference cycles. What does this mean? If I disable the garbage collector (`gc.disable()`) and I do something like this: ``` a = 'hi' a = 'hello' ``` will `'hi'` remain in memory? Do I need to free the memory by myself? What I understood from that sentence is that the gc is an extra tool made up expecially to catch reference cycles and if it is disabled the memory is still automatically cleaned using the reference counters of the objects but the reference cycles will not be managed. Is that right?