Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get the list of registered atexit functions in Python3?

In Python, I can use the atexit module to register function to be executed when Python exits. Is there a way to retrieve the list of registered exit handlers?

like image 918
Charles Brunet Avatar asked Apr 16 '13 16:04

Charles Brunet


People also ask

What is atexit in Python?

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.

What is Exit handlers?

Exit handler allows a library to do shutdown cleanup (thus of global data structure) without the main program being aware of that need.


1 Answers

here is a pure-python way to access the registered functions (the callable objects), but not the arguments they would be called with. It's a bit of a hack, but for debugging and the like, it will do just fine :

Python 3.5.3 (default, Jul  9 2020, 13:00:10) 
[GCC 6.3.0 20170516] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import atexit
>>> class Capture:
...     def __init__(self):
...         self.captured = []
...     def __eq__(self, other):
...         self.captured.append(other)
...         return False
... 
>>> c = Capture()
>>> atexit.unregister(c)
>>> print(c.captured)
[<function <lambda> at 0x7fc47631d730>, <built-in function write_history_file>]
>>> atexit.unregister(c.captured[0])  # this will work

How it works: as documented, atexit.unregister(c) removes any occurrence of c from the callback list. It does so by comparing each callback in turn with c for equality. This leads to the call c.__eq__(other), with other being the callback (this call is never skipped, as the other way around raises NotImplemented). Capture.__eq__ then copies its argument.

like image 80
BCarvello Avatar answered Oct 17 '22 09:10

BCarvello