Last active
May 27, 2019 14:38
-
-
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)
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
''' | |
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()) |
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
''' | |
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")) |
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
''' | |
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