Created
November 27, 2014 00:44
-
-
Save sttts/15c93690f837c58c9d63 to your computer and use it in GitHub Desktop.
Add optional parameters to a Python generator
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
# Add optional parameters to a decorator. | |
# | |
# Usage: | |
# | |
# Start with a normal decorator without parameters, e.g. | |
# | |
# def decorator(f): | |
# ... | |
# | |
# Add additional parameters with default value and use @optionally_parametrized_decorator, e.g. | |
# | |
# @optionally_parametrized_decorator | |
# def decorator(f, x=42, y=7): | |
# ... | |
# | |
# Then you can use the resulting decorator without _and_ with parameters, e.g. | |
# | |
# @decorator | |
# def f(a, b, c): | |
# ... | |
# | |
# @decorator(x=1, y=2) | |
# def f(a, b, c): | |
# ... | |
# | |
def optionally_parametrized_decorator(orig_decorator): | |
def decorator_or_decorator_func(orig_handler=None, **decorator_kwargs): | |
def decorator_wrap(orig_handler): | |
return orig_decorator(orig_handler, **decorator_kwargs) | |
# Python decorator magic: when orig_handler!=None is passed, we know | |
# that the decorator was called without parameters, i.e. like @with_valid_from_header. | |
# If the decorator is used as with_valid_from_header(min_api_version=2), then | |
# python will call this function without direct orig_handler parameter, but only with the | |
# min_api_version. | |
if orig_handler: | |
return decorator_wrap(orig_handler) | |
else: | |
return decorator_wrap | |
return decorator_or_decorator_func |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment