Skip to content

Instantly share code, notes, and snippets.

@SlyCodePanda
Last active May 27, 2019 14:38
Show Gist options
  • Save SlyCodePanda/d5dd4dbd07e173944238c6e6a4c3885f to your computer and use it in GitHub Desktop.
Save SlyCodePanda/d5dd4dbd07e173944238c6e6a4c3885f to your computer and use it in GitHub Desktop.
A step-by-step of how decorators work in Python (ref: Decoding the mysterious Python Decorator - Preyansh Shah)
'''
Functions can return other functions.
Lets look at an example of how inner functions can use the enclosing scope of the outer function.
Known in Python as "Closure".
'''
def outer_func(name):
def inner_func():
return "We are using the name {} inside inner_func".format(name)
return inner_func
out = outer_func("Renee")
print(out())
'''
Now let's create an actual decorator!
A decorator is nothing but a function wrapped around another function.
'''
def get_txt(name):
return "my name is {}".format(name)
def lets_decorate(func):
def func_wrapper(name):
return "Hi there, {0}. How are you?".format(func(name))
return func_wrapper
my_output = lets_decorate(get_txt)
print(my_output("Renee"))
'''
Fortunately, Python provides a better way of creating decorators through some syntactic sugar.
'''
def lets_decorate(func):
def func_wrapper(name):
return "Hi there, {0}. How are you?".format(func(name))
return func_wrapper
@lets_decorate
def get_txt(name):
return "my name is {}".format(name)
print(get_txt("Dan"))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment