What is the atexit.unregister method in Python?
The atexit module
atextit is a module in Python that performs clean-up operations upon the interpreter’s termination. This module provides functions similar to shutdown hooks in Java. The registered functions (also called handlers) are executed automatically upon the termination of the interpreter. The functions registered via this module are not executed when a program is terminated by a signal that Python does not handle. The os.exit() command is called, or the Python fatal internal error is detected. The handlers/functions are executed in reverse order with reference to the order in which they were registered.
The unregister() method
The unregister() method removes the given function from the list of functions to be executed at termination. Every occurrence of the given function is removed from the list of the registered handlers if it was registered multiple times.
Syntax
atexit.unregister(func)
func: This is the function to be removed.
Example
import atexitdef func_1(args):print("Executing func_1 with argument - %s" % (args,))def func_2():print("Executing func_2 with no arguments")atexit.register(func_1, [1,2,3])atexit.register(func_2)print("Hello Educative")atexit.unregister(func_2)
Explanation
- Line 1: We import the
atexitmodule. - Lines 3-4: The
func_1function is defined. This takesargsas an argument and prints it. - Lines 6-7: The
func_2function is defined with no arguments and prints a string. - Line 9: The
func_1function is registered as an exit handler using theregistermethod where we pass the argument as a positional argument. - Line 10: The
func_2function is registered as an exit handler using theregistermethod. As the function accepts no arguments, no parameters are passed as arguments in theregistermethod. - Line 12: The
printstatement is executed. - Line 14: The
func_2function is unregistered from the list of exit handlers using theunregistermethod.
When we run the code, only func_1 is executed since func_2 is removed.