简体   繁体   中英

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)

I asked another question awhile ago and it got answered splendidly. But another different question popped up...how do I make it to not show this in interactive idle:

在此输入图像描述

But to show this:

在此输入图像描述

What you are looking for here is functools.wraps , this is a decorator located in the functools module that makes sure the signature, name and pretty much all other metadata of the decorated function is retained after decoration:

from functools import wraps

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM