如何将参数传递给python d

2024-04-26 00:33:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我将要编写一个函数decorator,它接受一个参数并返回一个decorator,这个decorator可以用来控制单参数函数的参数类型。我希望在传递的参数的类型错误的情况下会发生提升错误。你知道吗

def typecontrol(num_type): 
    def wrapper_function(num):
        if isinstance(num, num_type):
            return num
        else:
            raise TypeError

    return wrapper_function

@typecontrol(float)
def myfunc(num):
    print(num)

例如,myfunc(9.123)应该打印9.123,myfunc(9)应该引发一个错误。但它总是引发类型错误。你知道吗


Tags: 函数类型参数returnifdeftype错误
2条回答

typecontrol将是一个函数,返回修饰符,而不是修饰符本身。您需要一个额外的嵌套函数:

def typecontrol(num_type):
    def decorator(f):
        def wrapper_function(num):
            if isinstance(num, num_type):
                f(num)
            else:
                raise TypeError
        return wrapper_function
    return decorator

@typecontrol(float)
def myfunc(num):
    print(num)

如果typecheck通过,包装函数将负责调用包装函数,而不是返回typechecked参数。你知道吗

在编写的代码中,num实际上是您要修饰的函数,因此您要检查函数是否是(在本例中)的实例float。你知道吗

一些例子:

>>> myfunc(3.0)
3.0
>>> myfunc("foo")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "tmp.py", line 7, in wrapper_function
    raise TypeError
TypeError

正如其他人所评论的那样,在here中可以找到关于编写带参数的装饰器的一个很好的解释。你知道吗

但是,似乎您想要强制类型(我以前在Python中也遇到过类似的麻烦),因此根据您的用例,我可能会推荐两个选项:

  1. 如果要确保在运行时之前键入的程序正确,请使用^{} static type checker。你知道吗
  2. 如果您需要在运行时分析/验证输入值,我强烈建议使用pydantic包。它允许您创建“类似结构”的对象(类似于NamedTupledataclass),这些对象将强制执行运行时类型检查,并在运行时使用python3.6+类型提示适当地强制输入。文档和一些有用的例子可以在here中找到。你知道吗

根据您的用例,我希望这两个都能有所帮助!你知道吗

相关问题 更多 >