Python函數裝飾器高級用法
本文轉載自微信公眾號「dongfanger」,作者dongfanger。轉載本文請聯系dongfanger公眾號。
在了解了Python函數裝飾器基礎知識和閉包之后,開始正式學習函數裝飾器。
典型的函數裝飾器
以下示例定義了一個裝飾器,輸出函數的運行時間:
函數裝飾器和閉包緊密結合,入參func代表被裝飾函數,通過自由變量綁定后,調用函數并返回結果。
使用clock裝飾器:
- import time
- from clockdeco import clock
- @clock
- def snooze(seconds):
- time.sleep(seconds)
- @clock
- def factorial(n):
- return 1 if n < 2 else n*factorial(n-1)
- if __name__=='__main__':
- print('*' * 40, 'Calling snooze(.123)')
- snooze(.123)
- print('*' * 40, 'Calling factorial(6)')
- print('6! =', factorial(6)) # 6!指6的階乘
輸出結果:
這是裝飾器的典型行為:把被裝飾的函數換成新函數,二者接受相同的參數,而且返回被裝飾的函數本該返回的值,同時還會做些額外操作。
值得注意的是factorial()是個遞歸函數,從結果來看,每次遞歸都用到了裝飾器,打印了運行時間,這是因為如下代碼:
- @clock
- def factorial(n):
- return 1 if n < 2 else n*factorial(n-1)
等價于:
- def factorial(n):
- return 1 if n < 2 else n*factorial(n-1)
- factorial = clock(factorial)
factorial引用的是clock(factorial)函數的返回值,也就是裝飾器內部函數clocked,每次調用factorial(n),執行的都是clocked(n)。
疊放裝飾器
- @d1
- @d2
- def f():
- print("f")
等價于:
- def f():
- print("f")
- f = d1(d2(f))
參數化裝飾器
怎么讓裝飾器接受參數呢?答案是:創建一個裝飾器工廠函數,把參數傳給它,返回一個裝飾器,然后再把它應用到要裝飾的函數上。
示例如下:
- registry = set()
- def register(active=True):
- def decorate(func):
- print('running register(active=%s)->decorate(%s)'
- % (active, func))
- if active:
- registry.add(func)
- else:
- registry.discard(func)
- return func
- return decorate
- @register(active=False)
- def f1():
- print('running f1()')
- # 注意這里的調用
- @register()
- def f2():
- print('running f2()')
- def f3():
- print('running f3()')
register是一個裝飾器工廠函數,接受可選參數active默認為True,內部定義了一個裝飾器decorate并返回。需要注意的是裝飾器工廠函數,即使不傳參數,也要加上小括號調用,比如@register()。
再看一個示例:
- import time
- DEFAULT_FMT = '[{elapsed:0.8f}s] {name}({args}) -> {result}'
- # 裝飾器工廠函數
- def clock(fmt=DEFAULT_FMT):
- # 真正的裝飾器
- def decorate(func):
- # 包裝被裝飾的函數
- def clocked(*_args):
- t0 = time.time()
- # _result是被裝飾函數返回的真正結果
- _result = func(*_args)
- elapsed = time.time() - t0
- name = func.__name__
- args = ', '.join(repr(arg) for arg in _args)
- result = repr(_result)
- # **locals()返回clocked的局部變量
- print(fmt.format(**locals()))
- return _result
- return clocked
- return decorate
- if __name__ == '__main__':
- @clock()
- def snooze(seconds):
- time.sleep(seconds)
- for i in range(3):
- snooze(.123)
這是給典型的函數裝飾器添加了參數fmt,裝飾器工廠函數增加了一層嵌套,示例中一共有3個def。
標準庫中的裝飾器
Python內置了三個用于裝飾方法的函數:property、classmethod和staticmethod,這會在將來的文章中講到。本文介紹functools中的三個裝飾器:functools.wraps、functools.lru_cache和functools.singledispatch。
functools.wraps
Python函數裝飾器在實現的時候,被裝飾后的函數其實已經是另外一個函數了(函數名等函數屬性會發生改變),為了不影響,Python的functools包中提供了一個叫wraps的裝飾器來消除這樣的副作用(它能保留原有函數的名稱和函數屬性)。
示例,不加wraps:
- def my_decorator(func):
- def wrapper(*args, **kwargs):
- '''decorator'''
- print('Calling decorated function...')
- return func(*args, **kwargs)
- return wrapper
- @my_decorator
- def example():
- """Docstring"""
- print('Called example function')
- print(example.__name__, example.__doc__)
- # 輸出wrapper decorator
加wraps:
- import functools
- def my_decorator(func):
- @functools.wraps(func)
- def wrapper(*args, **kwargs):
- '''decorator'''
- print('Calling decorated function...')
- return func(*args, **kwargs)
- return wrapper
- @my_decorator
- def example():
- """Docstring"""
- print('Called example function')
- print(example.__name__, example.__doc__)
- # 輸出example Docstring
functools.lru_cache
lru是Least Recently Used的縮寫,它是一項優化技術,把耗時的函數的結果保存起來,避免傳入相同的參數時重復計算。
示例:
- import functools
- from clockdeco import clock
- @functools.lru_cache()
- @clock
- def fibonacci(n):
- if n < 2:
- return n
- return fibonacci(n-2) + fibonacci(n-1)
- if __name__=='__main__':
- print(fibonacci(6))
優化了遞歸算法,執行時間會減半。
注意,lru_cache可以使用兩個可選的參數來配置,它的簽名如下:
- functools.lru_cache(maxsize=128, typed=False)
maxsize:最大存儲數量,緩存滿了以后,舊的結果會被扔掉。
typed:如果設為True,那么會把不同參數類型得到的結果分開保存,即把通常認為相等的浮點數和整型參數(如1和1.0)區分開。
functools.singledispatch
Python3.4的新增語法,可以用來優化函數中的大量if/elif/elif。使用@singledispatch裝飾的普通函數會變成泛函數:根據第一個參數的類型,以不同方式執行相同操作的一組函數。所以它叫做single dispatch,單分派。
根據多個參數進行分派,就是多分派了。
示例,生成HTML,顯示不同類型的Python對象:
- import html
- def htmlize(obj):
- content = html.escape(repr(obj))
- return '<pre>{}</pre>'.format(content)
因為Python不支持重載方法或函數,所以就不能使用不同的簽名定義htmlize的變體,只能把htmlize變成一個分派函數,使用if/elif/elif,調用專門的函數,比如htmlize_str、htmlize_int等。時間一長htmlize會變得很大,跟各個專門函數之間的耦合也很緊密,不便于模塊擴展。
@singledispatch經過深思熟慮后加入到了標準庫,來解決這類問題:
- from functools import singledispatch
- from collections import abc
- import numbers
- import html
- @singledispatch
- def htmlize(obj):
- # 基函數 這里不用寫if/elif/elif來分派了
- content = html.escape(repr(obj))
- return '<pre>{}</pre>'.format(content)
- @htmlize.register(str)
- def _(text):
- # 專門函數
- content = html.escape(text).replace('\n', '<br>\n')
- return '<p>{0}</p>'.format(content)
- @htmlize.register(numbers.Integral)
- def _(n):
- # 專門函數
- return '<pre>{0} (0x{0:x})</pre>'.format(n)
- @htmlize.register(tuple)
- @htmlize.register(abc.MutableSequence)
- def _(seq):
- # 專門函數
- inner = '</li>\n<li>'.join(htmlize(item) for item in seq)
- return '<ul>\n<li>' + inner + '</li>\n</ul>'
@singledispatch裝飾了基函數。專門函數使用@<<base_function>>.register(<<type>>)裝飾,它的名字不重要,命名為_,簡單明了。
這樣編寫代碼后,Python會根據第一個參數的類型,調用相應的專門函數。
小結
本文首先介紹了典型的函數裝飾器:把被裝飾的函數換成新函數,二者接受相同的參數,而且返回被裝飾的函數本該返回的值,同時還會做些額外操作。接著介紹了裝飾器的兩個高級用法:疊放裝飾器和參數化裝飾器,它們都會增加函數的嵌套層級。最后介紹了3個標準庫中的裝飾器:保留原有函數屬性的functools.wraps、緩存耗時的函數結果的functools.lru_cache和優化if/elif/elif代碼的functools.singledispatch。
參考資料:
《流暢的Python》
https://github.com/fluentpython/example-code/tree/master/07-closure-deco
https://blog.csdn.net/liuzonghao88/article/details/103586634