當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Python functools.wraps()用法及代碼示例

函數工具是用於高階函數(作用於或返回其他函數的函數)的標準Python模塊。wraps()是一個裝飾器,應用於裝飾器的包裝函數。它更新wrapper函數看起來像wrapped通過處理諸如__name____doc__(文檔字符串)等。

用法: @functools.wraps(wrapped, assigned = WRAPPER_ASSIGNMENTS, updated = WRAPPER_UPDATES)

參數:
wrapped:要由包裝函數修飾的函數名稱。
assigned:Tuple,用於指定原始函數的哪些屬性直接分配給包裝函數上的匹配屬性。默認情況下設置為WRAPPER_ASSIGNMENTS(分配給包裝函數的__module__,__name__,__qualname__,__annotations__和__doc __(文檔字符串))
updated:Tuple指定包裝器函數的哪些屬性用原始函數中的相應屬性更新。默認情況下,設置為WRAPPER_UPDATES(這將更新包裝函數的__dict__,即實例字典)。


範例1:沒有functools.wraps()

def a_decorator(func):
    def wrapper(*args, **kwargs):
        """A wrapper function"""
        # Extend some capabilities of func 
        func() 
    return wrapper 
  
@a_decorator
def first_function():
    """This is docstring for first function"""
    print("first function") 
  
@a_decorator
def second_function(a):
    """This is docstring for second function"""
    print("second function") 
  
print(first_function.__name__) 
print(first_function.__doc__) 
print(second_function.__name__) 
print(second_function.__doc__)
輸出:
wrapper
A wrapper function
wrapper
A wrapper function

現在,如果我們寫help(first_function)help(second_function)

print("First Function") 
help(first_function) 
  
print("\nSecond Function") 
help(second_function)
輸出:
First Function
Help on function wrapper in module __main__:

wrapper(*args, **kwargs)
    A wrapper function


Second Function
Help on function wrapper in module __main__:

wrapper(*args, **kwargs)
    A wrapper function

雖然上麵的代碼在邏輯上可以正常工作,但是如果您正在編寫API或庫,並且有人想知道函數的函數以及函數的名稱,或者隻是鍵入help(yourFunction),請考慮一下這一點,它將始終顯示包裝函數的名稱和文檔字符串。如果您對不同的函數使用了相同的包裝器函數,則這將更加令人困惑,因為它將為每個函數顯示相同的詳細信息。

理想情況下,它應該顯示包裝函數的名稱和文檔字符串,而不是包裝函數。手動解決方案是分配__name____doc__返回之前在包裝函數中添加屬性。

def a_decorator(func):
    def wrapper(*args, **kwargs):
        """A wrapper function"""
        # Extend some capabilities of func 
        func() 
    wrapper.__name__ = func.__name__ 
    wrapper.__doc__ = func.__doc__ 
    return wrapper 
  
@a_decorator
def first_function():
    """This is docstring for first function"""
    print("first function") 
  
@a_decorator
def second_function(a):
    """This is docstring for second function"""
    print("second function") 
  
print(first_function.__name__) 
print(first_function.__doc__) 
print(second_function.__name__) 
print(second_function.__doc__)
輸出:
first_function
This is docstring for first function
second_function
This is docstring for second function

這解決了問題,但是如果再次鍵入help(yourFunction),該怎麽辦,

print("First Function") 
help(first_function) 
  
print("\nSecond Function") 
help(second_function)

對於first_function:help(first_function)

輸出:
First Function
Help on function first_function in module __main__:

first_function(*args, **kwargs)
    This is docstring for first function


Second Function
Help on function second_function in module __main__:

second_function(*args, **kwargs)
    This is docstring for second function

如您所見,它仍然存在問題,即函數的簽名,它顯示了包裝函數為每個函數使用的簽名(此處為通用簽名)。同樣,如果要實現許多裝飾器,則必須為它們中的每一個編寫這些行。
因此,為了節省時間並提高可讀性,我們可以使用functools.wraps()作為包裝器函數的裝飾器。

示例(帶有functools.wraps())

from functools import wraps 
  
def a_decorator(func):
    @wraps(func) 
    def wrapper(*args, **kwargs):
        """A wrapper function"""
  
        # Extend some capabilities of func 
        func() 
    return wrapper 
  
@a_decorator
def first_function():
    """This is docstring for first function"""
    print("first function") 
  
@a_decorator
def second_function(a):
    """This is docstring for second function"""
    print("second function") 
  
print(first_function.__name__) 
print(first_function.__doc__) 
print(second_function.__name__) 
print(second_function.__doc__)
輸出:
first_function
This is docstring for first function
second_function
This is docstring for second function

現在,如果我們輸入help(first_function)--

print("First Function") 
help(first_function) 
  
print("\nSecond Function") 
help(second_function)
輸出:
First Function
Help on function first_function in module __main__:

first_function()
    This is docstring for first function


Second Function
Help on function second_function in module __main__:

second_function(a)
    This is docstring for second function


相關用法


注:本文由純淨天空篩選整理自manishkhurana大神的英文原創作品 Python | functools.wraps() function。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。