Sunday, November 17, 2024
Google search engine
HomeLanguagesPython Exit handlers (atexit)

Python Exit handlers (atexit)

atexit is a module in python which contains two functions register() and unregister(). The main role of this module is to perform clean up upon interpreter termination. Functions that are registered are automatically executed upon interpreter termination. Whenever a program is killed by a signal not handled by Python, when os.exit() is called, or Python fatal internal error is detected, the functions registered via this module are not executed.

  • register(): Register function takes a function as an argument that is to be executed at interpreter termination. If there are multiple functions passed as arguments e.g. (fun1(), fun2()..) then there execution will be in reverse order (…fun2(), fun1()). The execution occurs in last in first out (LIFO) concept.

Syntax: atexit.register(fun, *args, **kwargs) 

Parameters: First the function name is mentioned and then any arguments for that function is passed. The parameters are separated using ‘, ‘. 

Return: This function returns the called fun and hence the calling can be traced.

  • Note: This function can also be used as a decorator. 

# Example 1: 

Python3




# Python program to demonstrate
# atexit module
 
 
import atexit
 
names = ['Geeks', 'for', 'Geeks']
 
def hello(name):
    print (name)
 
for name in names:
 
    # Using register()
    atexit.register(hello, name)


Output :

Geeks
for
Geeks

# Example 2: Using register as a decorator 

Python3




# Python program to demonstrate
# atexit module
 
 
import atexit
 
# Using register() as a decorator
@atexit.register
def goodbye():
    print("GoodBye.")


Output :

GoodBye.
  • unregister(): The unregister() function removes the specified fun from the functions defined in the program. It provides a surety that the fun will not be called when the interpreter terminates.

Syntax: atexit.unregister(fun) 

Parameters: The function may or may not contain any parameter. If any present then the fun name is to be specified. 

Return: No return.

Example: 

Python3




# Python program to demonstrate
# atexit module
 
 
import atexit
 
names = ['Geeks', 'for', 'Geeks']
 
def hello(name):
    print (name)
 
for name in names:
 
    # Using unregister()
    atexit.unregister(hello)


Output :

No Output

RELATED ARTICLES

Most Popular

Recent Comments