Python帶參數的裝飾器
在裝飾器函數裏傳入參數
# -*- coding: utf-8 -*- # 2017/12/2 21:38 # 這不是什麽黑魔法,你只需要讓包裝器傳遞參數: def a_decorator_passing_arguments(function_to_decorate): def a_wrapper_accepting_arguments(arg1, arg2): print("I got args! Look:", arg1, arg2) function_to_decorate(arg1, arg2) return a_wrapper_accepting_arguments # 當你調用裝飾器返回的函數時,也就調用了包裝器,把參數傳入包裝器裏, # 它將把參數傳遞給被裝飾的函數裏. @a_decorator_passing_arguments def print_full_name(first_name, last_name): print("My name is", first_name, last_name) print_full_name("Peter", "Venkman") # 輸出: #I got args! Look: Peter Venkman #My name is Peter Venkman
在Python裏方法和函數幾乎一樣.唯一的區別就是方法的第一個參數是一個當前對象的(self
)
也就是說你可以用同樣的方式來裝飾方法!只要記得把self
加進去:
def method_friendly_decorator(method_to_decorate): def wrapper(self, lie): lie = lie - 3 # 女性福音 :-) return method_to_decorate(self, lie) return wrapper class Lucy(object): def __init__(self): self.age = 32 @method_friendly_decorator def sayYourAge(self, lie): print("I am %s, what did you think?" % (self.age + lie)) l = Lucy() l.sayYourAge(-3) #輸出: I am 26, what did you think?
如果你想造一個更通用的可以同時滿足方法和函數的裝飾器,用*args,**kwargs
就可以了
def a_decorator_passing_arbitrary_arguments(function_to_decorate): # 包裝器接受所有參數 def a_wrapper_accepting_arbitrary_arguments(*args, **kwargs): print("Do I have args?:") print(args) print(kwargs) # 現在把*args,**kwargs解包 # 如果你不明白什麽是解包的話,請查閱: # http://www.saltycrane.com/blog/2008/01/how-to-use-args-and-kwargs-in-python/ function_to_decorate(*args, **kwargs) return a_wrapper_accepting_arbitrary_arguments @a_decorator_passing_arbitrary_arguments def function_with_no_argument(): print("Python is cool, no argument here.") function_with_no_argument() #輸出 #Do I have args?: #() #{} #Python is cool, no argument here. @a_decorator_passing_arbitrary_arguments def function_with_arguments(a, b, c): print(a, b, c) function_with_arguments(1,2,3) #輸出 #Do I have args?: #(1, 2, 3) #{} #1 2 3 @a_decorator_passing_arbitrary_arguments def function_with_named_arguments(a, b, c, platypus="Why not ?"): print("Do %s, %s and %s like platypus? %s" %(a, b, c, platypus)) function_with_named_arguments("Bill", "Linus", "Steve", platypus="Indeed!") #輸出 #Do I have args ? : #(‘Bill‘, ‘Linus‘, ‘Steve‘) #{‘platypus‘: ‘Indeed!‘} #Do Bill, Linus and Steve like platypus? Indeed! class Mary(object): def __init__(self): self.age = 31 @a_decorator_passing_arbitrary_arguments def sayYourAge(self, lie=-3): # 可以加入一個默認值 print("I am %s, what did you think ?" % (self.age + lie)) m = Mary() m.sayYourAge() #輸出 # Do I have args?: #(<__main__.Mary object at 0xb7d303ac>,) #{} #I am 28, what did you think?
把參數傳遞給裝飾器
好了,如何把參數傳遞給裝飾器自己?
因為裝飾器必須接收一個函數當做參數,所以有點麻煩.好吧,你不可以直接把被裝飾函數的參數傳遞給裝飾器.
在我們考慮這個問題時,讓我們重新回顧下:
# 裝飾器就是一個‘平常不過‘的函數 def my_decorator(func): print "I am an ordinary function" def wrapper(): print "I am function returned by the decorator" func() return wrapper # 因此你可以不用"@"也可以調用他 def lazy_function(): print "zzzzzzzz" decorated_function = my_decorator(lazy_function) #輸出: I am an ordinary function # 之所以輸出 "I am an ordinary function"是因為你調用了函數, # 並非什麽魔法. @my_decorator def lazy_function(): print "zzzzzzzz" #輸出: I am an ordinary function
看見了嗎,和"my_decorator
"一樣只是被調用.所以當你用@my_decorator
你只是告訴Python去掉用被變量my_decorator
標記的函數.
這非常重要!你的標記能直接指向裝飾器.
def decorator_maker(): print "I make decorators! I am executed only once: "+ "when you make me create a decorator." def my_decorator(func): print "I am a decorator! I am executed only when you decorate a function." def wrapped(): print ("I am the wrapper around the decorated function. " "I am called when you call the decorated function. " "As the wrapper, I return the RESULT of the decorated function.") return func() print "As the decorator, I return the wrapped function." return wrapped print "As a decorator maker, I return a decorator" return my_decorator # 讓我們建一個裝飾器.它只是一個新函數. new_decorator = decorator_maker() #輸出: #I make decorators! I am executed only once: when you make me create a decorator. #As a decorator maker, I return a decorator # 下面來裝飾一個函數 def decorated_function(): print "I am the decorated function." decorated_function = new_decorator(decorated_function) #輸出: #I am a decorator! I am executed only when you decorate a function. #As the decorator, I return the wrapped function # Let’s call the function: decorated_function() #輸出: #I am the wrapper around the decorated function. I am called when you call the decorated function. #As the wrapper, I return the RESULT of the decorated function. #I am the decorated function.
下面讓我們去掉所有可惡的中間變量:
def decorated_function(): print "I am the decorated function." decorated_function = decorator_maker()(decorated_function) #輸出: #I make decorators! I am executed only once: when you make me create a decorator. #As a decorator maker, I return a decorator #I am a decorator! I am executed only when you decorate a function. #As the decorator, I return the wrapped function. # 最後: decorated_function() #輸出: #I am the wrapper around the decorated function. I am called when you call the decorated function. #As the wrapper, I return the RESULT of the decorated function. #I am the decorated function.
讓我們簡化一下:
@decorator_maker() def decorated_function(): print "I am the decorated function." #輸出: #I make decorators! I am executed only once: when you make me create a decorator. #As a decorator maker, I return a decorator #I am a decorator! I am executed only when you decorate a function. #As the decorator, I return the wrapped function. #最終: decorated_function() #輸出: #I am the wrapper around the decorated function. I am called when you call the decorated function. #As the wrapper, I return the RESULT of the decorated function. #I am the decorated function.
看到了嗎?我們用一個函數調用"@
"語法!:-)
所以讓我們回到裝飾器的.如果我們在函數運行過程中動態生成裝飾器,我們是不是可以把參數傳遞給函數?
def decorator_maker_with_arguments(decorator_arg1, decorator_arg2): print "I make decorators! And I accept arguments:", decorator_arg1, decorator_arg2 def my_decorator(func): # 這裏傳遞參數的能力是借鑒了 closures. # 如果對closures感到困惑可以看看下面這個: # http://stackoverflow.com/questions/13857/can-you-explain-closures-as-they-relate-to-python print "I am the decorator. Somehow you passed me arguments:", decorator_arg1, decorator_arg2 # 不要忘了裝飾器參數和函數參數! def wrapped(function_arg1, function_arg2) : print ("I am the wrapper around the decorated function.\n" "I can access all the variables\n" "\t- from the decorator: {0} {1}\n" "\t- from the function call: {2} {3}\n" "Then I can pass them to the decorated function" .format(decorator_arg1, decorator_arg2, function_arg1, function_arg2)) return func(function_arg1, function_arg2) return wrapped return my_decorator @decorator_maker_with_arguments("Leonard", "Sheldon") def decorated_function_with_arguments(function_arg1, function_arg2): print ("I am the decorated function and only knows about my arguments: {0}" " {1}".format(function_arg1, function_arg2)) decorated_function_with_arguments("Rajesh", "Howard") #輸出: #I make decorators! And I accept arguments: Leonard Sheldon #I am the decorator. Somehow you passed me arguments: Leonard Sheldon #I am the wrapper around the decorated function. #I can access all the variables # - from the decorator: Leonard Sheldon # - from the function call: Rajesh Howard #Then I can pass them to the decorated function #I am the decorated function and only knows about my arguments: Rajesh Howard
上面就是帶參數的裝飾器.參數可以設置成變量:
c1 = "Penny" c2 = "Leslie" @decorator_maker_with_arguments("Leonard", c1) def decorated_function_with_arguments(function_arg1, function_arg2): print ("I am the decorated function and only knows about my arguments:" " {0} {1}".format(function_arg1, function_arg2)) decorated_function_with_arguments(c2, "Howard") #輸出: #I make decorators! And I accept arguments: Leonard Penny #I am the decorator. Somehow you passed me arguments: Leonard Penny #I am the wrapper around the decorated function. #I can access all the variables # - from the decorator: Leonard Penny # - from the function call: Leslie Howard #Then I can pass them to the decorated function #I am the decorated function and only knows about my arguments: Leslie Howard
你可以用這個小技巧把任何函數的參數傳遞給裝飾器.如果你願意還可以用*args,**kwargs
.但是一定要記住了裝飾器只能被調用一次.當Python載入腳本後,你不可以動態的設置參數了.當你運行import x
,函數已經被裝飾,所以你什麽都不能動了.
functools
模塊在2.5被引進.它包含了一個functools.wraps()
函數,可以復制裝飾器函數的名字,模塊和文檔給它的包裝器.
如何為被裝飾的函數保存元數據
解決方案:
使用標準庫functools中的裝飾器wraps 裝飾內部包裹函數,
可以 制定將原函數的某些屬性,更新到包裹函數的上面
其實也可以通過
wrapper.name = func.name
update_wrapper(wrapper, func, (‘name‘,’doc‘), (‘dict‘,))
f.__name__ 函數的名字
f.__doc__ 函數文檔字符串
f.__module__ 函數所屬模塊名稱
f.__dict__ 函數的屬性字典
f.__defaults__ 默認參數元組
f.__closure__ 函數閉包
>>> def f(): ... a=2 ... return lambda k:a**k ... >>> g=f() >>> g.__closure__ (<cell at 0x000001888D17F2E8: int object at 0x0000000055F4C6D0>,) >>> c=g.__closure__[0] >>> c.cell_contents 2
from functools import wraps,update_wrapper def log(level="low"): def deco(func): @wraps(func) def wrapper(*args,**kwargs): ‘‘‘ I am wrapper function‘‘‘ print("log was in...") if level == "low": print("detailes was needed") return func(*args,**kwargs) #wrapper.__name__ = func.__name__ #update_wrapper(wrapper, func, (‘__name__‘,‘__doc__‘), (‘__dict__‘,)) return wrapper return deco @log() def myFunc(): ‘‘‘I am myFunc...‘‘‘ print("myFunc was called") print(myFunc.__name__) print(myFunc.__doc__) myFunc() """ myFunc I am myFunc... log was in... detailes was needed myFunc was called """
如何定義帶參數的裝飾器
實現一個裝飾器,它用來檢查被裝飾函數的參數類型,裝飾器可以通過參數指明函數參數的類型,
調用時如果檢測出類型不匹配則拋出異常。
提取函數簽名python3 inspect.signature()
帶參數的裝飾器,也就是根據參數定制化一個裝飾器可以看生成器的工廠
每次調用typeassert,返回一個特定的裝飾器,然後用它去裝飾其他函數
>>> from inspect import signature >>> def f(a,b,c=1):pass >>> sig=signature(f) >>> sig.parameters mappingproxy(OrderedDict([(‘a‘, <Parameter "a">), (‘b‘, <Parameter "b">), (‘c‘, <Parameter "c=1">)])) >>> a=sig.parameters[‘a‘] >>> a.name ‘a‘ >>> a <Parameter "a"> >>> dir(a) [‘KEYWORD_ONLY‘, ‘POSITIONAL_ONLY‘, ‘POSITIONAL_OR_KEYWORD‘, ‘VAR_KEYWORD‘, ‘VAR_POSITIONAL‘, ‘__class__‘, ‘__delattr__‘, ‘__dir__‘, ‘__doc__‘, ‘__eq__‘, ‘__format__‘, ‘__ge__‘, ‘__getattribute__‘, ‘__gt__‘, ‘__hash__‘, ‘__init__‘, ‘__init_subclass__‘, ‘__le__‘, ‘__lt__‘, ‘__module__‘, ‘__ne__‘, ‘__new__‘, ‘__reduce__‘, ‘__reduce_ex__‘, ‘__repr__‘, ‘__setattr__‘, ‘__setstate__‘, ‘__sizeof__‘, ‘__slots__‘, ‘__str__‘, ‘__subclasshook__‘, ‘_annotation‘, ‘_default‘, ‘_kind‘, ‘_name‘, ‘annotation‘, ‘default‘, ‘empty‘, ‘kind‘, ‘name‘, ‘replace‘] >>> a.kind <_ParameterKind.POSITIONAL_OR_KEYWORD: 1> >>> a.default <class ‘inspect._empty‘> >>> c=sig.parameters[‘c‘] >>> c.default 1 >>> sig.bind(str,int,int) <BoundArguments (a=<class ‘str‘>, b=<class ‘int‘>, c=<class ‘int‘>)> >>> bargs=sig.bind(str,int,int) >>> bargs.arguments OrderedDict([(‘a‘, <class ‘str‘>), (‘b‘, <class ‘int‘>), (‘c‘, <class ‘int‘>)]) >>> bargs.arguments[‘a‘] <class ‘str‘> >>> bargs.arguments[‘b‘] <class ‘int‘>
from inspect import signature def typeassert(*ty_args,**ty_kargs): def decorator(func): #func ->a,b #d = {‘a‘:int,‘b‘:str} sig = signature(func) btypes = sig.bind_partial(*ty_args,**ty_kargs).arguments def wrapper(*args,**kargs): #arg in d,instance(arg,d[arg]) for name, obj in sig.bind(*args,**kargs).arguments.items(): if name in btypes: if not isinstance(obj,btypes[name]): raise TypeError(‘"%s" must be "%s"‘ %(name,btypes[name])) return func(*args,**kargs) return wrapper return decorator @typeassert(int,str,list) def f(a,b,c): print(a,b,c) f(1,‘abc‘,[1,2,3]) # f(1,2,[1,2,3])
如何實現屬性可修改的函數裝飾器
為分析程序內哪些函數執行時間開銷較大,我們定義一個帶timeout參數的函數裝飾器,裝飾功能如下:
1.統計被裝飾函數單詞調用運行時間
2.時間大於參數timeout的,將此次函數調用記錄到log日誌中
3.運行時可修改timeout的值。
解決方案:
python3 nolocal
為包裹函數添加一個函數,用來修改閉包中使用的自由變量.
python中,使用nonlocal訪問嵌套作用域中的變量引用,或者在python2中列表方式,這樣就不會在函數本地新建一個局部變量
from functools import wraps import time import logging def warn(timeout): # timeout = [timeout] def deco(func): def wrapper(*args,**kwargs): start = time.time() res = func(*args,**kwargs) used = time.time() -start if used > timeout: msg = ‘"%s" : %s > %s‘%(func.__name__,used,timeout) logging.warn(msg) return res def setTimeout(k): nonlocal timeout # timeout[0] = k timeout=k print("timeout was given....") wrapper.setTimeout = setTimeout return wrapper return deco from random import randint @warn(1.5) def test(): print("in test...") while randint(0,1): time.sleep(0.5) for _ in range(30): test() test.setTimeout(1) print("after set to 1....") for _ in range(30): test()
小練習:
#為了debug,堆棧跟蹤將會返回函數的 __name__ def foo(): print("foo") print(foo.__name__) #輸出: foo ######################################## # 如果加上裝飾器,將變得有點復雜 def bar(func): def wrapper(): print("bar") return func() return wrapper @bar def foo(): print("foo") print(foo.__name__) #輸出: wrapper ####################################### # "functools" 將有所幫助 import functools def bar(func): # 我們所說的"wrapper",正在包裝 "func", # 好戲開始了 @functools.wraps(func) def wrapper(): print("bar") return func() return wrapper @bar def foo(): print("foo") print(foo.__name__) #輸出: foo
Python帶參數的裝飾器