我们可以很容易地指定函数的返回类型,即使我们期望的类型作为它的参数之一提供:
from typing import TypeVar, Type, Union
T = TypeVar('T')
def to(t: Type[T], v) -> T:
return t(v)
s: str = to(str, 1)
i: int = to(str, 1) # Ok: Expected type 'int', got 'str' instead
但是,如果我们提供Union[str,int]作为第一个参数,它就不起作用了(不要看函数本身,我们可以用这个Union做一些更复杂的事情,即基于提供的Union构造pydantic模型)
G = Union[str, int]
g: G = to(G, 1) # Expected type 'Type[T]', got 'object' instead
那么,如何指定函数的返回类型应该是作为第一个参数提供的类型呢?即使我们提供的不是像int或str这样的纯类型,而是Union
更新
更确切地说,这是我想装饰的功能
from typing import Type, Union
from pydantic import validate_arguments, BaseModel
def py_model(t, v: dict):
def fabric():
def f(x):
return x
f.__annotations__['x'] = t
return validate_arguments(f)
f = fabric()
return f(v)
class Model1(BaseModel): foo: int
class Model2(BaseModel): bar: str
print(repr(py_model(Union[Model1, Model2], {'foo':1}))) # Model1(foo=1)
print(repr(py_model(Union[Model1, Model2], {'bar':1}))) # Model2(bar='1')
因此,当我调用py_模型(Union[Model1,Model2],…)时,我希望它将返回Model1或Model2中的一个,因此Union[Model1,Model2]
对
to
函数使用“Callable”而不是运算符来构造类型如何然后可以将Union类型的构造函数作为参数
这种实施的一个例子是:
上面的代码只在mypy中为
i2
引发一个错误相关问题 更多 >
编程相关推荐