Python memory management is straight forward. You don’t need to worry about memory management, as memory allocation and deallocation is automatic. one of the mechanisms of memory management is garbage collection. Let’s understand different aspects of garbage collection,
It is the process by which shared computer memory is cleaned which is currently being put to use by a running program when that program no longer needs that memory. With garbage collection, that freed memory can be used by another program.
There are two methods used by python for memory management −
Python’s garbage collection is automatic but in some programming languages, you have to clean objects yourself. In python, if you want you can delete objects manually.
>>> x = 9 >>> print(x) 9 >>> del x >>> print(x) Traceback (most recent call last): File "<pyshell#3>", line 1, in <module> print(x) NameError: name 'x' is not defined
Above we simply define one variable(x) and use it. During runtime, we delete the object(because everything in python is an object) and try to output it.
In the first two lines of the above program, object x is known. However, after the deletion of the object(x), we cannot print it anymore.
So from above, we can see that garbage collection is fully automated and we don’t need to worry about it. Let’s understand the above concept with another example. Every object in python like in the above code, object x has a reference count and a pointer to a type.
The reference count changes value depends on how we are using it, for example, if we assign the object x to another object y, its reference count increases to 2.
>>> some_list = [1, 2 ,3, 4, 5, 6, 7, 8, 9] >>> #Reference count of some_list = 1 >>> other_list = some_list >>> #Reference count = 2 >>> #This will also increases if we pass the object as an assignment >>> list_total = sum(some_list) >>> # If we put the object in a list, reference count will also increase >>> list_of_list = [some_list, some_list, some_list] >>> >>> #Let's check the reference count of object "some_list" >>> import sys >>> sys.getrefcount(some_list) 6
Above is one good example to understand reference counting of memory management in python. We create one object “some_list” (reference count = 1), we assign it to another object (ref. count = 2), we set the object as an argument(ref. count =3) and later we put the object into a list where occurrence of object is three times (ref. count =6). Later when we try to get the reference count of object “some_list”, we get 6.
>>> import sys >>> sys.getrefcount(some_list) 6 >>> >>> del list_of_list >>> sys.getrefcount(some_list) 3 >>> del some_list >>> sys.getrefcount(some_list) Traceback (most recent call last): File "<pyshell#17>", line 1, in <module> sys.getrefcount(some_list) NameError: name 'some_list' is not defined