How to Use atexit in Python for Cleanup Actions
Use the
atexit module in Python to register functions that you want to run automatically when your program ends. Call atexit.register(your_function) to add a cleanup function that runs on normal program termination.Syntax
The atexit module provides a simple way to register functions that will be called when the Python program is about to exit normally.
Key parts:
atexit.register(function, *args, **kwargs): Registers a function to be called with optional arguments when the program exits.- The registered functions run in the reverse order of their registration.
python
import atexit def cleanup(): print('Cleaning up before exit') atexit.register(cleanup)
Example
This example shows how to register multiple functions with atexit. They will run automatically when the program finishes.
python
import atexit def goodbye(): print('Goodbye!') def cleanup_temp_files(): print('Removing temporary files...') atexit.register(cleanup_temp_files) atexit.register(goodbye) print('Program is running...')
Output
Program is running...
Goodbye!
Removing temporary files...
Common Pitfalls
What can go wrong:
- Functions registered with
atexitonly run on normal program exit, not if the program crashes or is killed. - Exceptions in registered functions are ignored but printed to stderr, so errors might be missed.
- Registering functions that depend on resources already closed can cause errors.
Wrong way: Registering a function that raises an exception without handling it.
Right way: Handle exceptions inside the registered function to avoid silent failures.
python
import atexit def faulty_cleanup(): raise Exception('Oops!') atexit.register(faulty_cleanup) print('Exiting program...')
Output
Exiting program...
Exception ignored in: <function faulty_cleanup at 0x7f8c2c0d1ee0>
Traceback (most recent call last):
File "<stdin>", line 4, in faulty_cleanup
Exception: Oops!
Quick Reference
| Function | Description |
|---|---|
| atexit.register(func, *args, **kwargs) | Register a function to be called on program exit |
| Registered functions run in reverse order | Last registered runs first |
| Functions run only on normal exit | Not called on crashes or kill signals |
| Exceptions in registered functions | Are printed but do not stop exit process |
Key Takeaways
Use atexit.register() to run cleanup functions automatically when your program ends.
Registered functions run in reverse order of registration.
atexit functions only run on normal program exit, not on crashes or forced termination.
Handle exceptions inside your atexit functions to avoid silent errors.
atexit is useful for closing resources or saving state before the program exits.