I'm trying to get my head around Decorators in Python. I've got a handle on what they are for from various answers [ex] on SO: to run code before and/or after a decorated function without modifying the function itself. That said, I'm having trouble understanding what it means to return a function object.
What is the difference between returning the return value of a function and returning the function object? I get that a reference to the function itself is returned, but what is the utility of this behavior?
I didn't use the @Decorator
syntax below as I'm still learning that.
For example:
def some_func():
print('returning 1')
return 1
def Decorator(func):
def Wrapper():
print('doing something first')
val = func()
print('doing something after')
return val
return Wrapper
Decorated_func = Decorator(some_func)
Decorated_func()
Stepping through this in PythonTutor: calling Decorated_func() shows that Wrapper
has a return value of 1
and Decorator
has a return value of Wrapper
. Does that mean that Decorator
actually has a return value of 1
when Decorated_func()
is called? I would have thought that the syntax for that behavior would be (within Decorator
) return Wrapper()
. What is the point of returning a function object?