What is Memory Leak in Python?

Python Tutorials

Summary: In this tutorial, we will learn what memory leak is in Python and how can we prevent it from occurring in our Python programs.

What is Memory Leak?

Unlike C++, Python itself takes care of the management of the memory. The garbage collector in Python keeps track of the references and deletes the unreferenced object (object no longer in use or gone out of scope) to free up the memory.

However, the garbage collector sometimes fails to delete the unreferenced object from the memory.

The memory allocated to the object remains occupied, but can no longer be accessed (since all the referenced have been deleted), causing a memory leak.

When the Memory Leak occurs in Python?

Memory Leaks can occur in many instances depending on the logic of the code but in Python, it has been observed that it often occurs in the following two situations:

  1. When we define or declare an object in class scope rather than the instance scope.
  2. When a circular reference is created among two objects.

Consider the following Python code for instance:

class App:
    def __init__(self):
        print("Cloud App Opened")
        
    def __del__(self):
        print("Cloud App closed")

class Phone:
    app = None
    
    def __init__(self):
        print("Switching on the Phone")
        self.__class__.app = App()
        
    def __del__(self):
        print("Switching off the Phone")
        

#creating an object of Phone
phone = Phone()

#deleting the object
del phone

Output:

Switching on the Phone
Cloud App Opened
Switching off the Phone

When we delete the object phone, only the __del__ of the phone was invoked, the __del__ method of the data member object app remains unexecuted.

It means the data member object app was not destroyed and is still occupying space in the memory.

Although the data members are destroyed (garbage collected) along with the object, it didn’t happen in this case. It is so because the app is not an instance variable but a class variable.

When the instance of any class is deleted or destroyed, the garbage collector only collects the instance variables to free up the memory. The class members in class scope remain alive in the memory, resulting in the leak of the memory.

How to Avoid Memory Leak in Python?

To avoid memory leaks, we as a programmer should try to ensure that no two objects are referring to each other to form a circular reference.

If we need to do that, we must make a weak circular reference so that it can be destroyed by the Python.

Moreover, we should avoid using class variables unless necessary.

In case, if we are defining any class variable then we should manually delete them in the __del__ method.

Example:

class App:
    def __init__(self):
        print("Cloud App opened")
        
    def __del__(self):
        print("Cloud App closed")

class Phone:
    app = None
    
    def __init__(self):
        print("Switching on the Phone")
        self.__class__.app = App()
 
    def __del__(self):

        #delete the app object manually
        del self.__class__.app
        print("Switching off the Phone")
        

#creating an object of Phone
phone = Phone()

#deleting the object
del phone

Output:

Switching on the Phone
Cloud App opened
Cloud App closed
Switching off the Phone

This python code works fine (it would have been better if the app were an instance variable) because it ensures that all objects in memory are finally deleted.

In analogy, if we open any cloud app on our phone and switch off the mobile, the app would still be running in the cloud. So it’s better to turn off all running apps before switching off the phone.

Leave a Reply

Your email address will not be published. Required fields are marked *