Python has the atexit built-in API for registering functions to be executed on program exit.
In my case, I have an API function that can be imported and used, which creates a temporary directory that needs to be cleaned-up when the function returns (or raises an exception).
Rather than using try-finally, is there any conventional way to register a function to be executed on function exit?
The simplest way to do this reusably is just to use a decorator:
For example:
You could also pass
argsandkwargstoactionif you think they're going to be needed for the clean-up.