Welcome to our comprehensive guide on Python Garbage Collection! Let's dive into the world of automatic memory management in Python. This tutorial is designed for beginners and intermediates, so don't worry if some concepts seem familiar.
Garbage Collection (GC) is a mechanism in Python that automatically frees up memory occupied by objects that are no longer in use. Unlike languages like C and C++, Python doesn't require manual memory deallocation.
Python uses a reference-counting garbage collector. The collector counts the number of references (or variables) pointing to an object. If the count reaches zero, the object is considered garbage and is freed.
Let's see how Python's garbage collector works with some examples.
a = [1, 2, 3]
print("List created:", a)
def some_function():
b = a
print("List passed to function:", b)
some_function()
print("List after function call:", a)Output:
List created: [1, 2, 3]
List passed to function: [1, 2, 3]
List after function call: [1, 2, 3]
In this example, we created a list a and passed it to a function some_function(). Although the list b in the function points to the same memory location as a, both variables are still reachable, so the list is not garbage collected.
a = [1, 2, 3]
print("List created:", a)
def some_function():
b = a
print("List passed to function:", b)
del b # Unbind the reference to the list, making it unreachable
some_function()
print("List after function call:", a)
# Wait for GC to run
import gc
gc.collect()
print("List after garbage collection:", a)Output:
List created: [1, 2, 3]
List passed to function: [1, 2, 3]
List after function call: [1, 2, 3]
List after garbage collection: []
In this example, we created a list a, passed it to a function, and unbound the reference b to the list inside the function using the del keyword. This makes the list unreachable, so it is garbage collected after calling gc.collect().
If an object has no references pointing to it, what happens to it during garbage collection in Python?
That's all for today! We hope you found this lesson on Python's Garbage Collection informative. Stay tuned for more engaging and practical programming tutorials right here at CodeYourCraft. Happy coding! 💻🎉