What is the atexit.register method in Python?
Overview
In Python, the atextit module is used to perform clean-up operations on the interpreter termination. This module provides functions similar to shutdown hooks in Java. The
The functions registered via this module are not executed when a program is terminated by a signal that is not handled by Python, when os.exit() is called, or when Python fatal internal error is detected. Thee handlers or functions are executed in reverse order with reference to the order in which they were registered.
The register() method
The register() method registers the given function to be executed at termination. This method also accepts the arguments that need to be passed to the given function.
- The execution of the functions registered is in reverse order, meaning last-in, first-out order.
- If an exception occurs while the exit handlers are being executed, a traceback is produced and the exception information is preserved. The final exception to be raised is re-raised once all exit handlers have had a chance to run.
- The same function can be registered as exit handlers multiple times.
The given function can also be registered using the @atexit.register decorator. For example:
@atexit.register
def func_4():
print("Executing func_4 with no arguments")
Syntax
atexit.register(func, *args, **kwargs)
Parameters
func: This is the function to be registered.argsandkwargs: These are the function arguments.
Return value
This function returns the called func. The calling can therefore be traced.
Example
import atexitdef func_1(args):print("Executing func_1 with argument - %s" % (args,))def func_2():print("Executing func_2 with no arguments")def func_3(arg1, arg2):print("Executing func_3 with arg1 - %s, arg2 - %s" % (arg1, arg2))print("Hello Educative")atexit.register(func_1, [1,2,3])atexit.register(func_2)atexit.register(func_3, arg1="hello", arg2="educative")
Explanation
- Line 1: We import the
atexitmodule. - Lines 3–4: We define the
func_1, which takesargsas an argument, and we print it. - Lines 6–7: We define the
func_2with no arguments and print a string. - Lines 9–10: We define the
func_3, which takesarg1andarg2as arguments, and we print it. - Line 12: We execute the
printstatement. - Line 14: We register
func_1as an exit handler using theregistermethod, where we pass the argument as a positional argument. - Line 15: We register
func_2as an exit handler using theregistermethod. As the function accepts no arguments, no parameters are passed as arguments in theregistermethod. - Line 16: We register
func_3as an exit handler using theregistermethod where we pass the arguments as keyword arguments.
When we run the code, func_3 is executed first, then func_2, and finally func_1 is executed.