Skip to content

Instantly share code, notes, and snippets.

@nicr9
Created January 20, 2016 23:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nicr9/7b18c005cf27d173a55b to your computer and use it in GitHub Desktop.
Save nicr9/7b18c005cf27d173a55b to your computer and use it in GitHub Desktop.
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
@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")
@ChittaSwathi
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