Run Cleanup Code on Exit With Python's atexit
Key Takeaways
The video demonstrates how to use Python's atexit module to run cleanup code on exit, including registering functions and handling exceptions.
Full Transcript
Sometimes when your program exits, you want to run some clean-up code. And [clears throat] depending on your program, you might be able to do that when the user hits the quit button, but there is another way. The at exit module allows you to register one or more functions to be called when the program exits. This is done by passing a function reference into at exits register handler call. When your code is done, Python calls the registered function for you. A few caveats. First, this doesn't get called if there's an exception. Doesn't get called if someone control sees your program, or if the exit is triggered by OS exit. So, it's useful for clean exits, but not for messy ones. There are ways of trapping interrupt signals like control C, so you could write a signal handler as well as the at exit handler. Second, the at exit takes a reference to a function, which means the function can't take arguments. But, the functools module has a feature called partials that allows you to wrap functions with a reference, getting around this restriction.
Original Description
Download your free Python Cheat Sheet here: https://realpython.com/cheatsheet
Free Python Skill Test with instant level + learning plan: https://realpython.com/skill-test
Want to learn faster? Become a Python Expert with unlimited access to 5,000+ tutorials, videos, and exercises: https://realpython.com/start
Listen to the full episode at https://realpython.com/podcasts/rpp/290 or wherever you get podcasts -- with Chris Trudeau (hosted by Chris Bailey).
🐍 Become a Python expert with real-world tutorials, on-demand courses, interactive quizzes, and 24/7 access to a community of experts at https://realpython.com
▰▰▰▰▰▰▰▰▰▰▰▰▰▰▰▰▰▰▰▰
🐍 Start Here → https://realpython.com/start
🗺️ Guided Learning Paths → https://realpython.com/learning-paths
🎧 Real Python Podcast → https://realpython.com/podcast
📚 Python Books → https://realpython.com/books
📖 Python Reference → https://realpython.com/ref
🧑💻 Quizzes & Exercises → https://realpython.com/quizzes
🎓 Live Courses: https://realpython.com/live
⭐️ Reviews & Learner Stories: https://realpython.com/learner-stories
▰▰▰▰▰▰▰▰▰▰▰▰▰▰▰▰▰▰▰▰
Related Reads
📰
📰
📰
📰
Getting Started with GoFr: the easiest go framework for microservices
Medium · Programming
Understanding HTTP: The Backbone of the Web
Medium · Programming
Laravel Authentication in 2026: Breeze vs Jetstream vs Fortify vs Custom — The Decision You Can’t…
Medium · Programming
15 Spring Boot Annotations Every Senior Developer Should Know
Medium · Programming
🎓
Tutor Explanation
DeepCamp AI