Run Cleanup Code on Exit With Python's atexit

Real Python · Beginner ·🔧 Backend Engineering ·4mo ago

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 ▰▰▰▰▰▰▰▰▰▰▰▰▰▰▰▰▰▰▰▰
Sign in to unlock AI tutor explanation · ⚡30

The atexit module in Python allows you to run cleanup code when your program exits. You can register one or more functions to be called when the program exits, but there are some caveats to consider, such as exceptions and interrupt signals.

Key Takeaways
  1. Import the atexit module
  2. Define a cleanup function
  3. Register the cleanup function with atexit.register
  4. Use functools.partial to pass arguments to the cleanup function if needed
💡 The atexit module is useful for clean exits, but not for messy ones, and you may need to use signal handlers to trap interrupt signals like control C.

Related Reads

📰
Cache-Control vs. ETag: What Each One Actually Controls
Learn the difference between Cache-Control and ETag headers to optimize browser caching and reduce unnecessary requests
Dev.to · Susumu Takahashi
📰
JavaScript Parameters, Arguments, Default & Rest Parameters
Learn the difference between JavaScript parameters and arguments, and how to use default and rest parameters to write more flexible functions
Dev.to · Megalraja
📰
Automated Testing in Backend Development: A Complete Guide from Unit Tests to Fuzz Testing
Learn how to ensure confidence in backend development changes with automated testing, from unit tests to fuzz testing
Dev.to · Mehrad Sadeghi
📰
I Missed @Service in Node.js, So I Built It with Express
Learn how to build a service-like feature in Node.js with Express, inspired by the author's experience with missing the @Service decorator from other frameworks
Dev.to · Mike Jung
Up next
Unlock CRAZY Performance: Native Code Compilation No JNI! #shorts #quarkusinsights #projectpanama
Quarkusio
Watch →