我想定义一个函数,使返回值在不同场合具有不同的类型。
不过,我想在函数签名中包含它返回某些内容的指示。
我知道一种方法是使用 Union
,例如:
from typing import Union
def f(x: int) -> Union[str, int]:
return x if x > 0 else "this is zero"
但就我而言,我手头没有可能的输出类型列表。
我尝试使用:
def f(x: int) -> object:
return some_other_func(x)
问题是,现在当我尝试使用此函数时,IDE 告诉我我有一个键入错误:
y: SomeClass = f(42)
Error: Expected type 'SomeClass', got 'object' instead
那么 - 如何在函数签名中指示f
正在返回某个值,而不指示值的类型?
从键入文档中,可以使用 Any
,例如:
from typing import Any
def f(x: int) -> Any:
return some_other_func(x)