/  Technology   /  Python   /  Whenever Python exists, why isn’t all the memory de-allocated?
Python-Interview-Questions-and-Answers(i2tutorials.com)

Whenever Python exists, why isn’t all the memory de-allocated?

Ans. Using ‘del’ keyword we can try to remove some particular object. But Python is a ‘garbage collector’ that means there is no guarantee that the object is actually removed from the memory when you use ‘Del some Big Object’. In fact ‘Del some Big Object’ is not only pointless but also it is a bad style.

According to ‘Python official documentation’ you can force the garbage collector to release referring memory with gc.collect().  It is known, where Python will definitely leak memory when you declare circular references in your object declarations and implement a custom __del__ destructor method in one of these classes. When Python exit, the object referenced from global namespaces of Python modules are not always deallocated. So, Python doesn’t recognize and free circular memory references before using the garbage collector.

If you are using some resource like a file then you should instead use the method that definitely indicate you are not using this resource anymore like my FileHandle. Close (). Or delete all explicit reference.

Generally, Python is free for the most of the object as soon as their reference count reaches zero. This never happens in the case of circular references, so the garbage collector periodically walks memory and frees circularly-referenced objects. Also, it’s not possible to forget to free memory like C drive, but it is possible to keep a reference hanging somewhere. However, Python is aggressive about cleaning up the memory on exit and does try to destroy every single object.

If you forcefully delete some object in Python on deallocation then you need to use the atexit module and have to register one or more exit functions to handle the process of deletion. All memory allocation on the heap ends up with high water-mark. Python’s internal optimizations are very complicated for allocating small objects. The small object allocator was moved to using anonymous memory maps instead of the heap, so it should perform better at releasing memory.

Leave a comment