對於Python裝飾器使用的一些建議

來源:互聯網
上載者:User

對於Python裝飾器使用的一些建議

   這篇文章主要介紹了對於Python裝飾器使用的一些建議,裝飾器是Python學習進階中的重要知識,需要的朋友可以參考下

  裝飾器基本概念

  大家都知道裝飾器是一個很著名的設計模式,經常被用於 AOP (面向切面編程)的情境,較為經典的有插入日誌,效能測試,交易處理,Web許可權校正, Cache等。

  Python 語言本身提供了裝飾器文法(@),典型的裝飾器實現如下:

  ?

1

2

3

@function_wrapper

def function():

pass

  @實際上是 python2.4 才提出的文法糖,針對 python2.4 以前的版本有另一種等價的實現:

  ?

1

2

3

4

def function():

pass

 

function = function_wrapper(function)

  裝飾器的兩種實現

  函數封裝器 - 經典實現

  ?

1

2

3

4

5

6

7

8

def function_wrapper(wrapped):

def _wrapper(*args, **kwargs):

return wrapped(*args, **kwargs)

return _wrapper

 

@function_wrapper

def function():

pass

  類封裝器 - 易於理解

  ?

1

2

3

4

5

6

7

8

9

class function_wrapper(object):

def __init__(self, wrapped):

self.wrapped = wrapped

def __call__(self, *args, **kwargs):

return self.wrapped(*args, **kwargs)

 

@function_wrapper

def function():

pass

  函數(function)自省

  當我們談到一個函數時,通常希望這個函數的屬性像其文檔上描述的那樣,是被明確定義的,例如__name__ 和__doc__ 。

  針對某個函數應用裝飾器時,這個函數的屬性就會發生變化,但這並不是我們所期望的。

  ?

1

2

3

4

5

6

7

8

9

10

11

def function_wrapper(wrapped):

def _wrapper(*args, **kwargs):

return wrapped(*args, **kwargs)

return _wrapper

 

@function_wrapper

def function():

pass

 

>>> print(function.__name__)

_wrapper

  python 標準庫提供了functools.wraps(),來解決這個問題。

  ?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

import functools

 

def function_wrapper(wrapped):

@functools.wraps(wrapped)

def _wrapper(*args, **kwargs):

return wrapped(*args, **kwargs)

return _wrapper

 

@function_wrapper

def function():

pass

 

>>> print(function.__name__)

function

  然而,當我們想要擷取被封裝函數的參數(argument)或原始碼(source code)時,同樣不能得到我們想要的結果。

  ?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

import inspect

 

def function_wrapper(wrapped): ...

 

@function_wrapper

def function(arg1, arg2): pass

 

>>> print(inspect.getargspec(function))

ArgSpec(args=[], varargs='args', keywords='kwargs', defaults=None)

 

>>> print(inspect.getsource(function))

@functools.wraps(wrapped)

def _wrapper(*args, **kwargs):

return wrapped(*args, **kwargs)

  封裝類方法(@classmethod)

  當封裝器(@function_wrapper)被應用於@classmethod時,將會拋出如下異常:

  ?

1

2

3

4

5

6

7

8

9

10

11

12

13

class Class(object):

@function_wrapper

@classmethod

def cmethod(cls):

pass

 

Traceback (most recent call last):

File "<stdin>", line 1, in <module>

File "<stdin>", line 3, in Class

File "<stdin>", line 2, in wrapper

File ".../functools.py", line 33, in update_wrapper

setattr(wrapper, attr, getattr(wrapped, attr))

AttributeError: 'classmethod' object has no attribute '__module__'

  因為@classmethod在實現時,缺少functools.update_wrapper需要的某些屬性。這是functools.update_wrapper在 python2 中的 bug,3.2版本已被修複,參考 http://bugs.python.org/issue3445。

  然而,在 python3 下執行,另一個問題出現了:

  ?

1

2

3

4

5

6

7

8

9

10

11

12

13

class Class(object):

@function_wrapper

@classmethod

def cmethod(cls):

pass

 

>>> Class.cmethod()

Traceback (most recent call last):

File "classmethod.py", line 15, in <module>

Class.cmethod()

File "classmethod.py", line 6, in _wrapper

return wrapped(*args, **kwargs)

TypeError: 'classmethod' object is not callable

  這是因為封裝器認定被封裝的函數(@classmethod )是可以直接被調用的,但事實並不一定是這樣的。被封裝的函數實際上可能是描述符(descriptor ),意味著為了使其可調用,該函數(描述符)必須被正確地綁定到某個執行個體上。關於描述符的定義,可以參考 https://docs.python.org/2/howto/descriptor.html。

  總結 - 簡單並不意味著正確

  儘管大家實現裝飾器所用的方法通常都很簡單,但這並不意味著它們一定是正確的並且始終能正常工作。

  如同上面我們所看到的,functools.wraps() 可以幫我們解決__name__ 和__doc__ 的問題,但對於擷取函數的參數(argument)或原始碼( source code )則束手無策。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.