是否有可能创建一个类似于
from typing import Union, Literal
class Foo:
bar: Union[str, int]
qux: Literal["str", "int"]如果qux是Literal["str"],那么bar是str类型,如果qux是Literal["int"],那么bar是int类型吗?有可能给它加注释吗?
我知道typing.overload,但我不认为它与本例相关
发布于 2021-07-12 11:43:00
Python的typing系统通常不支持依赖类型。然而,也有可能模仿一些具体的案例。
对于较低数量的依赖类型,可以枚举这些情况。这需要使单个类型成为通用类型:
from typing import Union, Literal, Generic, TypeVar
Bar = TypeVar("Bar", str, int)
Qux = TypeVar("Qux", Literal["str"], Literal["int"])
class GenericFoo(Generic[Bar, Qux]):
bar: Bar
qux: Qux
# not always needed – used to infer types from instantiation
def __init__(self, bar: Bar, qux: Qux): pass然后,可以定义依赖项。
Union:Foo = Union[GenericFoo[str,字面“str”],GenericFoo[int,文字“int”] f: Foo f=GenericFoo(“1”,"str") f= GenericFoo(2,"int") f=GenericFoo(“3”,"int")overload(GenericBar,Qux):bar: bar: Qux @重载def __init__(self,bar: str,qux:文本“str”):pass @overload def __init__(self,bar: int,qux:字面“int”):pass def __init__(self,Bar : Bar,qux: Qux):# type:忽略传递https://stackoverflow.com/questions/68346391
复制相似问题