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?
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.
Exit handler allows a library to do shutdown cleanup (thus of global data structure) without the main program being aware of that need.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With