Skip to content

Instantly share code, notes, and snippets.

Created January 20, 2016 23:23
What would you like to do?
Python decorators with nested functions
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
def a(text):
print text
@with_params("and desert you!")
def b(text):
print text
if __name__ == "__main__":
a(2, 3)
b("fizz bang")
Copy link

Why does it only have to be nested functions? Isn't there any other way of implementing it?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment