Hi folks,
In this post I talk about a good way to perform actions when your Python program completes. For example you may want to clean up temporary files created by program or close database connections or other resources resources when your program terminates. You may want to do this regardless of whether the program finishes successfully or crashes due to an error. An excellent way to perform such clean-up tasks automatically is to use the atexit module. Here is an example below of how to use it in a class below.
import atexit class Foo: def __init__(self): atexit.register(self.goodbye) x = 5 def goodbye(self): print('You are leaving the program') f = Foo()
If you run the following code, you will see the message ‘You are leaving the program’ just before the program exits.
Here is another example where we intentionally cause the program to crash.
import atexit class Bar: def __init__(self): atexit.register(self.goodbye) x = 5 / 0 # error! def goodbye(self): print('You are leaving the program') f = Bar()
If you run this program, you will see the error, but nevertheless still see the message ‘You are leaving the program’ printed before the program exits.
You can read more about atexit in the Python documentation.
That’s it for now. Happy software development.