The Python modifier and functools Python modifier are syntactically Sugar (Syntactic Sugar), that is:
@decorator@wrapdef func(): pass
Is a short form of the following syntax:
def func(): passfunc = decorator(wrap(func))
The modifier has two main problems:
-
Modifier used to modify who
-
Who can act as modifier
Modifier
The most common use of modifier is to modify the newly defined function. in the 0x0d context manager, the context manager mainly aimsFinish the aftermath more elegantlyThe modifier is usually used to extend the behavior or attributes of a function:
def log(func): def wraper(): print("INFO: Starting {}".format(func.__name__)) func() print("INFO: Finishing {}".format(func.__name__)) return wraper@logdef run(): print("Running run...")run()
INFO: Starting runRunning run...INFO: Finishing run
Modifier
In addition to the modifier function, the new defined class (PEP 3.0) is added after Python 3129, but the modification to the class attribute can be implemented through Metaclasses or inheritance, the newly added class modifier is mainly for Jython and IronPython, but its syntax is quite consistent:
from time import sleep, timedef timer(Cls): def wraper(): s = time() obj = Cls() e = time() print("Cost {:.3f}s to init.".format(e - s)) return obj return wraper@timerclass Obj: def __init__(self): print("Hello") sleep(3) print("Obj")o = Obj()
HelloObjCost 3.005s to init.
Class as modifier
The above two examples use functions as modifiers because functions can be called (callable) decorator (wrap (func )). In addition to functions, we can also define the classes that can be called, as long as the _ call _ method is added:
class HTML(object): """ Baking HTML Tags! """ def __init__(self, tag="p"): print("LOG: Baking Tag <{}>!".format(tag)) self.tag = tag def __call__(self, func): return lambda: "<{0}>{1}
".format(self.tag, func(), self.tag) @HTML("html")@HTML("body")@HTML("p")def body(): return "Hello"print(body())
LOG: Baking Tag !LOG: Baking Tag !LOG: Baking Tag !
Hello
Pass parameters
In actual use, we may need to pass parameters to the modifier or to the modified function (or class. According to the syntax, as long as the decorator in the modifier @ decorator is callable, it is reasonable if decorator (123) returns a new callable function, the above @ HTML ('HTML ') is an example. the following uses the flask route modifier as an example to illustrate how to pass parameters to the modifier:
RULES = {}def route(rule): def decorator(hand): RULES.update({rule: hand}) return hand return decorator @route("/")def index(): print("Hello world!")def home(): print("Welcome Home!")home = route("/home")(home)index()home()print(RULES)
Hello world!Welcome Home!{'/':
, '/home':
}
Passing parameters to the modified function depends on how our modifier works. if we do not execute the modified function just as in the preceding example, we will return the original modulus of the modifier, you do not need to process it. (you can treat the function as a normal value ):
@route("/login")def login(user = "user", pwd = "pwd"): print("DB.findOne({{{}, {}}})".format(user, pwd))login("hail", "python")
DB.findOne({hail, python})
If you need to execute it in the modifier, you need to change it slightly:
def log(f): def wraper(*args, **kargs): print("INFO: Start Logging") f(*args, **kargs) print("INFO: Finish Logging") return wraper@logdef run(hello = "world"): print("Hello {}".format(hello))run("Python")
INFO: Start LoggingHello PythonINFO: Finish Logging
Functools
Since the modifier wraps the function (or class) and returns the result again: func = decorator (func), some information of the original function (or class) may be changed, the preceding HTML modifier is used as an example:
@HTML("body")def body(): """ return body content """ return "Hello, body!"print(body.__name__)print(body.__doc__)
LOG: Baking Tag !
None
Because body = HTML ("body") (body), while HTML ("body "). _ call _ () returns a lambda function, so the body has been replaced with lambda. although all functions are executable, some attributes in the original defined body are, for example, _ doc _/_ name _/_ module _ is replaced (in this example, _ module _ is not changed because all files are in the same file. ). To solve this problem, Python provides the functools standard library, including the update_wrapper and wraps methods (source code ). Update_wrapper is used to assign the original function information to the function returned by the modifier:
from functools import update_wrapper"""functools.update_wrapper(wrapper, wrapped[, assigned][, updated])"""class HTML(object): """ Baking HTML Tags! """ def __init__(self, tag="p"): print("LOG: Baking Tag <{}>!".format(tag)) self.tag = tag def __call__(self, func): wraper = lambda: "<{0}>{1}
".format(self.tag, func(), self.tag) update_wrapper(wraper, func) return wraper @HTML("body")def body(): """ return body content! """ return "Hello, body!"print(body.__name__)print(body.__doc__)
LOG: Baking Tag !body return body content!
Interestingly, the usage of update_wrapper is like a modifier. Therefore, functools. wraps uses functools. partial (remember the partial application in functional programming !) Turn it into a modifier:
from functools import update_wrapper, partialdef my_wraps(wrapped): return partial(update_wrapper, wrapped=wrapped)def log(func): @my_wraps(func) def wraper(): print("INFO: Starting {}".format(func.__name__)) func() print("INFO: Finishing {}".format(func.__name__)) return wraper@logdef run(): """ Docs' of run """ print("Running run...")print(run.__name__)print(run.__doc__)
run Docs' of run
Reference
-
Function programming of Python modifier