There is an option in python where you can execute a function when the interpreter terminates.
Consider this below example, save the code in a file and run it.
import atexit
def aa_atexit():
print('atexit of this aa called')
atexit.register(aa_atexit)
print('started')
$ python3 atexit_example.py
Output:
started
atexit of this aa called
aa_atexit
is called just before the interpreter terminates.
As per python documentation:
Theatexit
module defines functions to register and unregister cleanup functions. Functions thus registered are automatically executed upon normal interpreter termination.atexit
runs these functions in the reverse order in which they were registered; if you registerA
,B
, andC
, at interpreter termination time they will be run in the orderC
,B
,A
.
Hence we can register functions to perform cleanup tasks in with atexit. Also, these functions are executed FILO/LIFO (first in last out or last in first out) order.
import atexit
class CC:
def __init__(self):
atexit.register(self.gg)
def gg(self):
print('atexit of cc called')
class BB:
def __init__(self):
atexit.register(self.hh)
def hh(self):
print('atexit of bb called')
def bb(self):
CC()
print('bb called')
def aa_atexit():
print('atexit of this aa called')
atexit.register(aa_atexit)
BB().bb()
print('started')
Here we registered the aa_atexit
function first, then created an object of BB class where we registered a function with atexit for BB class and then when function bb()
of BB class was called, we registered a function with atexit for CC class by initializing the CC class.
So the sequence of functions registered with atexit is aa_atexit()
, BB.hh()
and CC.gg()
. When we run this program with a python interpreter, we know that CC.gg()
should be called first and then BB.hh()
and at last aa_atexit()
. Let's run the code and see.
output:
rana@brahma$ python atexit_experiment.py bb called started atexit of cc called atexit of bb called atexit of this aa called
Just like how we can register the function with atexit, we can unregister the functions as well.
https://mail.python.org/pipermail/python-bugs-list/2009-January/069209.html