python - 裝飾器使用過程中的誤區

來源:互聯網
上載者:User

標籤:python

裝飾器基本概念

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


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


@function_wrapperdef function():    pass


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


def function():    passfunction = function_wrapper(function)
裝飾器的兩種實現


函數封裝器 - 經典實現


def function_wrapper(wrapped):    def _wrapper(*args, **kwargs):        return wrapped(*args, **kwargs)    return _wrapper @function_wrapperdef function():    pass


類封裝器 - 易於理解


class function_wrapper(object):    def __init__(self, wrapped):        self.wrapped = wrapped    def __call__(self, *args, **kwargs):        return self.wrapped(*args, **kwargs)@function_wrapperdef function():    pass
函數(function)自省

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


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


def function_wrapper(wrapped):    def _wrapper(*args, **kwargs):        return wrapped(*args, **kwargs)    return _wrapper @function_wrapperdef function():    pass >>> print(function.__name__)_wrapper


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


import functools def function_wrapper(wrapped):    @functools.wraps(wrapped)    def _wrapper(*args, **kwargs):        return wrapped(*args, **kwargs)    return _wrapper @function_wrapperdef function():    pass >>> print(function.__name__)function


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


import inspect def function_wrapper(wrapped): ...@function_wrapperdef 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時,將會拋出如下異常:


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下執行,另一個問題出現了:


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()可以幫我們解決namedoc 的問題,但對於擷取函數的參數(argument)或原始碼(source code)則束手無策。


以上問題,wrapt都可以幫忙解決,詳細用法可參考其官方文檔: http://wrapt.readthedocs.org


本文作者系OneAPM工程師曾靈敏,想要閱讀更多技術文章,請訪問OneAPM官方技術部落格。

python - 裝飾器使用過程中的誤區

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.