Skip to content

Instantly share code, notes, and snippets.

@mara004
Created August 8, 2025 13:45
Show Gist options
  • Select an option

  • Save mara004/88835190749e5657f9c26490dab8b4f2 to your computer and use it in GitHub Desktop.

Select an option

Save mara004/88835190749e5657f9c26490dab8b4f2 to your computer and use it in GitHub Desktop.
Exit hanlder for function
# SPDX-FileCopyrightText: 2025 geisserml <geisserml@gmail.com>
# SPDX-License-Identifier: Apache-2.0 OR BSD-3-Clause
import functools
class finally_decorator:
def __init__(self, callback):
self._callback = callback
def __call__(self, func):
@functools.wraps(func)
def wrapped(*args, **kwargs):
try:
return func(*args, **kwargs)
finally:
self._callback()
return wrapped
@finally_decorator(lambda: print("Exit test"))
def test(arg, kwarg=1):
print(f"Enter test({arg}, {kwarg})")
test(0)
@mara004
Copy link
Author

mara004 commented Oct 1, 2025

Higher-level solution for globals cleanup: https://gist.github.com/mara004/c1ad00953cf9f4946f45b6dcc9d4778e

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment