Python atexit — ELI5
Imagine you’re leaving a hotel room. Before you walk out the door, you have a checklist: turn off the lights, close the windows, put the key on the desk. You do these things every time, right before you leave.
Python’s atexit module works the same way — it lets you register “cleanup tasks” that run automatically right before your program exits.
Maybe your program opened a file and needs to save final data. Or it connected to a database and should disconnect cleanly. Or it created temporary files that should be deleted.
Instead of remembering to clean up at every possible exit point in your code, you register a function with atexit once, and Python promises to call it when the program is done.
How simple is it?
import atexit
def say_goodbye():
print("Cleaning up... goodbye!")
atexit.register(say_goodbye)
That’s it. No matter how your program ends (normally, at least), say_goodbye runs automatically.
One thing to remember
atexit is your program’s “checkout checklist” — register cleanup functions once, and Python handles calling them at shutdown, so you don’t have to worry about forgetting.
See Also
- Python Bisect Sorted Lists How Python's bisect module finds things in sorted lists the way you'd find a word in a dictionary — by jumping to the middle.
- Python Contextlib How Python's contextlib module makes the 'with' statement work for anything, not just files.
- Python Copy Module Why copying data in Python isn't as simple as it sounds, and how the copy module prevents sneaky bugs.
- Python Dataclass Field Metadata How Python dataclass fields can carry hidden notes — like sticky notes on a filing cabinet that tools read automatically.
- Python Datetime Handling Why dealing with dates and times in Python is trickier than it sounds — and how the datetime module tames the chaos