簡體   English   中英

如何顯示裝飾器的原始參數

[英]How to show the original arguments for a decorator

from inspect import signature
from typing import get_type_hints

def check_range(f):
    def decorated(*args, **kwargs): #something should be modified here
        counter=0
        # use get_type_hints instead of __annotations__
        annotations = get_type_hints(f)
        # bind signature to arguments and get an 
        # ordered dictionary of the arguments
        b = signature(f).bind(*args, **kwargs).arguments            
        for name, value in b.items():
            if not isinstance(value, annotations[name]):
                msg = 'Not the valid type'
                raise ValueError(msg)
            counter+=1

        return f(*args, **kwargs) #something should be modified here
    return decorated

@check_range
def foo(a: int, b: list, c: str):
    print(a,b,c)

我前一段時間問了另一個問題,得到了很好的回答。 但是又出現了另一個不同的問題......如何讓它在交互式空閑時不顯示:

在此輸入圖像描述

但要表明這一點:

在此輸入圖像描述

你在這里尋找的是functools.wraps ,這是一個位於functools模塊中的裝飾器,它確保裝飾后的簽名,名稱和幾乎所有其他元數據都被保留:

from functools import wraps

def check_range(f):
    @wraps(f)
    def decorated(*args, **kwargs):
        counter=0
        # rest as before

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM