Python decorators with nested functions
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 without_params(func): | |
""" | |
Outer function takes target function and returns a wrapped one. | |
""" | |
def _without_params(*args, **kwargs): | |
""" | |
Inner function takes target arguments and makes the call. | |
""" | |
return func("Never gonna run around") | |
return _without_params | |
def with_params(val): | |
""" | |
If you need to take params, it's the same but wrapped in another function. | |
This one takes the decorator parameters and returns a doubly wrapped function. | |
""" | |
def _with_params(func): | |
def __with_params(*args, **kwargs): | |
return func(val) | |
return __with_params | |
return _with_params | |
@without_params | |
def a(text): | |
print text | |
@with_params("and desert you!") | |
def b(text): | |
print text | |
if __name__ == "__main__": | |
a(2, 3) | |
b("fizz bang") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Why does it only have to be nested functions? Isn't there any other way of implementing it?