Firstly, I'm so sorry if this is a dupplicated question.
let's say I have a simple python code named decorator.py with decorator here:
def decorator(func):
def wrapper():
print("Before function.")
val = func()
print("After function.")
return val
return wrapper() # <- please pay attention to this line`
@decorator
def hello():
print("hello!")
@decorator
def good_bye():
print("good_bye!")
@decorator
def thank_you():
print("thank_you!")
@decorator
def thanks_a_lot():
print("thanks_a_lot!")
the result after running the code
Before function.
hello!
After function.
Before function.
good_bye!
After function.
Before function.
thank_you!
After function.
Before function.
thanks_a_lot!
After function.
[Finished in 46ms]
this mean, return wrapper() calls all my functions? what is the difference between wrapper() and wrapper in this case. I appreciate for your explaination.
I'm tring to run on debug mode to find out, but still got nothing, I hope I'll get a detail explaination
In this case calling wrapper() would immediately execute the function. if you just return wrapper, then you are returning the function itself so that it can be called later by another part of the code
EDIT
I am going to come up with a contrived example to illustrate what I mean in the above explanation:
An immediately executed function might be like this:
In the above case as you expect "Hello, World!" is printed immediately.
You can also reference functions in variables like:
In the above case we created a variable hello_function that references the same hello_world function and then LATER executes it with hello_function()
You could then do slick things like pass that function around to other functions creating higher order functions.