- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Why isn’t all memory freed when CPython exits?
CPython is the default and most widely used interpreter or implementation of Python. It is the original Python version and understands the code written using python specifications.
Python is quite serious about cleaning up memory on exit and does try to destroy every single object, but unfortunately objects referenced from the global namespaces of Python modules are not always deallocated when Python exits. The reason are circular references. There are also certain bits of memory that are allocated by the C library that are impossible to free. Use the atexit module to force Python to delete certain things on deallocation.
The atexit Module
However, if you want to force Python to delete certain things on deallocation use the atexit module. The atexit module defines functions to register and unregister cleanup functions. Functions thus registered are automatically executed upon normal interpreter termination. atexit runs these functions in the reverse order in which they were registered; if you register P, Q, and R, at interpreter termination time they will be run in the order R, Q, P.
Let us see how to install the atexit module in Python −
pip install atexit
Import atexit −
import atexit
Methods of the atexit module
Following are the methods −
atexit.register(func, *args, **kwargs) − Register func as a function to be executed at termination. Any optional arguments that are to be passed to func must be passed as arguments to register().
atexit.unregister(func) − Remove func from the list of functions to be run at interpreter shutdown. unregister() silently does nothing if func was not previously registered. If func has been registered more than once, every occurrence of that function in the atexit call stack will be removed
Example
Let us see an example −
try: with open('counterfile') as infile: _count = int(infile.read()) except FileNotFoundError: _count = 0 def incrcounter(n): global _count _count = _count + n def savecounter(): with open('counterfile', 'w') as outfile: outfile.write('%d' % _count) import atexit atexit.register(savecounter)
The above example demonstrates how a module can initialize a counter from a file when it is imported and save the counter’s updated value automatically when the program terminates without relying on the application making an explicit call into this module at termination.