python decorator
- What is a python decorator?
Usually the decorator is hinted with @
and looks like this, @_name_of_dectoration_func before the function needs to be decorated. - What is decorator really doing?
It’s actually calling anther function that seals the main_func and modify its functionality in this way or another. - Why this could be done?
Python defined function could take a function name as input and return a function cause anything in python is an object. The real function will not operated until ‘fun()’ is called. So we cam define a deco_fun(fun) then return a modified function. Finally we cal the modi_fun() and get a decorated functionality.
For example:
def decoratorFunction(fun):
'This is self-defined decortaor function'
def wrapFun():
print("Begins the modified acts 1")
fun()
print("Info: the function is modified")
return wrapFun
@decoratorFunction
fun()
# That is @decator is a shortway of saying fun = decoratorFun(fun)
Note that to pass a function name as argument and return this same function name could result in the doc of original function being re-written to wrapFun instead of fun.
# use this to find out
print(fun.__name__)
So inside the decorator function, use
@wraps(fun)
# Right before wrapFun is called
So the whole codes should be like:
from functools import wraps
def decoratorFunction(fun):
'This is self-defined decortaor function'
@wraps(fun)
def wrapFun():
print("Begins the modified acts 1")
fun()
print("Info: the function is modified")
return wrapFun
@decoratorFunction
fun()
print(fun.__name__)
Note that python methods could take fun(*args, **kargs) to broadly casting any unknown functions
Turn to Basics about decorators for more examples.