mar*_*lli 4 python type-hinting mypy python-typing
是否可以创建一个类似的类
from typing import Union, Literal
class Foo:
bar: Union[str, int]
qux: Literal["str", "int"]
Run Code Online (Sandbox Code Playgroud)
这样,如果qux是Literal["str"],则bar属于类型str,如果qux是Literal["int"],则bar属于类型int?可以注释一下吗?
我知道typing.overload,但我认为这与此示例无关
Python 系统通常不支持依赖类型typing。然而,可以模拟一些特定的情况。
对于数量较少的依赖类型,可以列举一些情况。这需要使各个类型通用:
\nfrom typing import Union, Literal, Generic, TypeVar\n\nBar = TypeVar("Bar", str, int)\nQux = TypeVar("Qux", Literal["str"], Literal["int"])\n\n\nclass GenericFoo(Generic[Bar, Qux]):\n bar: Bar\n qux: Qux\n\n # not always needed \xe2\x80\x93 used to infer types from instantiation\n def __init__(self, bar: Bar, qux: Qux): pass\nRun Code Online (Sandbox Code Playgroud)\n然后可以定义依赖关系
\nUnion其中一种情况:\nFoo = Union[GenericFoo[str, Literal["str"]], GenericFoo[int, Literal["int"]]]\n\nf: Foo\nf = GenericFoo("one", "str")\nf = GenericFoo(2, "int")\nf = GenericFoo("three", "int")\nRun Code Online (Sandbox Code Playgroud)\noverloading 实例化:\nclass GenericFoo(Generic[Bar, Qux]):\n bar: Bar\n qux: Qux\n\n @overload\n def __init__(self, bar: str, qux: Literal["str"]):\n pass\n\n @overload\n def __init__(self, bar: int, qux: Literal["int"]):\n pass\n\n def __init__(self, bar: Bar, qux: Qux): # type: ignore\n pass\nRun Code Online (Sandbox Code Playgroud)\n