Created
August 8, 2025 13:45
-
-
Save mara004/88835190749e5657f9c26490dab8b4f2 to your computer and use it in GitHub Desktop.
Exit hanlder for function
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# SPDX-FileCopyrightText: 2025 geisserml <[email protected]> | |
# 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) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
My initial motivation for this was to clean up global state, but refactoring to avoid globals in the first place turned out to be the better solution in that case.