歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Python - 裝飾器使用過程中的誤區

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

日期:2017/3/1 9:28:24   编辑:Linux編程

裝飾器基本概念

大家都知道裝飾器是一個很著名的設計模式,經常被用於AOP(面向切面編程)的場景,較為經典的有插入日志,性能測試,事務處理,Web權限校驗Cache等。

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

    @function_wrapper
    def function():
       pass

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

    def function():
        pass

    function = function_wrapper(function)

裝飾器的兩種實現

函數包裝器 - 經典實現

    def function_wrapper(wrapped):
        def _wrapper(*args, **kwargs):
            return wrapped(*args, **kwargs)
        return _wrapper 

    @function_wrapper
    def function():
        pass

類包裝器 - 易於理解

    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__

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

    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() ,來解決這個問題。

    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)時,同樣不能得到我們想要的結果。

    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時,將會拋出如下異常:

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

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

無需操作系統直接運行 Python 代碼 http://www.linuxidc.com/Linux/2015-05/117357.htm

CentOS上源碼安裝Python3.4 http://www.linuxidc.com/Linux/2015-01/111870.htm

《Python核心編程 第二版》.(Wesley J. Chun ).[高清PDF中文版] http://www.linuxidc.com/Linux/2013-06/85425.htm

《Python開發技術詳解》.( 周偉,宗傑).[高清PDF掃描版+隨書視頻+代碼] http://www.linuxidc.com/Linux/2013-11/92693.htm

Python腳本獲取Linux系統信息 http://www.linuxidc.com/Linux/2013-08/88531.htm

在Ubuntu下用Python搭建桌面算法交易研究環境 http://www.linuxidc.com/Linux/2013-11/92534.htm

Python 語言的發展簡史 http://www.linuxidc.com/Linux/2014-09/107206.htm

Python 的詳細介紹:請點這裡
Python 的下載地址:請點這裡

Copyright © Linux教程網 All Rights Reserved