python type函数返回类型,Python类型提示:函数返回类型,以参数形式给出,但类型是通用别名,例如Union...

We can specify easily return type of function, even if type we expect is provided as one of it's argument:

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

But it does not work if we provide Union[str, int] as first argument (do not see at function itself, we can do something more complex with this Union, i.e. construct pydantic model based on Union provided)

G = Union[str, int]

g: G = to(G, 1) # Expected type 'Type[T]', got 'object' instead

So how to specify that return type of function should be the one provided as first argument? Even if we provide not pure type like int or str, but also Union?

UPDATE

To be more precise there is the function i'd like to decorate

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')

So when I call py_model(Union[Model1, Model2], ...) I expect it will return one of Model1 or Model2 so Union[Model1, Model2]

解决方案

How about using a "Callable" for the to function, instead of the operator to construct the type?

You could then have a constructor for Union type as argument.

An example of such implementation would be:

from typing import Any, Callable, TypeVar, Type, Union

T = TypeVar('T')

V = TypeVar('V')

def to(t: Callable[[V], T], v: V) -> T:

return t(v)

G = Union[str, int]

def build_g(v:G) -> G:

return v if isinstance(v, int) else str(v)

s: str = to(str, 1)

i1: int = to(int, 1)

i2: int = to(str, 1) # Ok: Expected type 'int', got 'str' instead

g1: G = to(build_g, 1) # No error raised

g2: G = to(build_g, "2") # No error raised

The code above only raises an error in mypy for i2

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值