字段类型取决于其他字段的类型

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)

这样,如果quxLiteral["str"],则bar属于类型str,如果quxLiteral["int"],则bar属于类型int?可以注释一下吗?

我知道typing.overload,但我认为这与此示例无关

Mis*_*agi 5

Python 系统通常不支持依赖类型typing。然而,可以模拟一些特定的情况。

\n

对于数量较少的依赖类型,可以列举一些情况。这需要使各个类型通用:

\n
from 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\n
Run Code Online (Sandbox Code Playgroud)\n

然后可以定义依赖关系

\n
    \n
  • 作为Union其中一种情况:\n
    Foo = Union[GenericFoo[str, Literal["str"]], GenericFoo[int, Literal["int"]]]\n\nf: Foo\nf = GenericFoo("one", "str")\nf = GenericFoo(2, "int")\nf = GenericFoo("three", "int")\n
    Run Code Online (Sandbox Code Playgroud)\n
  • \n
  • 通过overloading 实例化:\n
    class 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\n
    Run Code Online (Sandbox Code Playgroud)\n
  • \n
\n