Last active
January 27, 2018 10:05
-
-
Save jbasko/c85d3b8a6d3d11a463d2c6a2702ca91f to your computer and use it in GitHub Desktop.
Generator-aware decorator factory
This file contains 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
def context_entering_decorator(context_manager): | |
""" | |
Creates a context-entering decorator that does not fail to do its job | |
if the underlying function is actually a generator function. | |
""" | |
def decorator(func): | |
if inspect.isgeneratorfunction(func): | |
@functools.wraps(func) | |
def wrapped(*args, **kwargs): | |
with context_manager(): | |
yield from func(*args, **kwargs) | |
else: | |
@functools.wraps(func) | |
def wrapped(*args, **kwargs): | |
with context_manager(): | |
return func(*args, **kwargs) | |
return wrapped | |
return decorator |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment