Skip to content

Instantly share code, notes, and snippets.

@jbasko
Last active January 27, 2018 10:05
Show Gist options
  • Save jbasko/c85d3b8a6d3d11a463d2c6a2702ca91f to your computer and use it in GitHub Desktop.
Save jbasko/c85d3b8a6d3d11a463d2c6a2702ca91f to your computer and use it in GitHub Desktop.
Generator-aware decorator factory
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