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

Type of field dependent on type of other field

是否可以创建一个class喜欢

from typing import Union, Literal

class Foo:
    bar: Union[str, int]
    qux: Literal["str", "int"]

这样,如果 quxLiteral["str"],则 barstr 类型,如果 quxLiteral["int"],那么 barint 类型?可以注释吗?

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

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, Literal["str"]], GenericFoo[int, Literal["int"]]]
    
    f: Foo
    f = GenericFoo("one", "str")
    f = GenericFoo(2, "int")
    f = GenericFoo("three", "int")
    
  • 通过 overload 实例化:
    class GenericFoo(Generic[Bar, Qux]):
        bar: Bar
        qux: Qux
    
        @overload
        def __init__(self, bar: str, qux: Literal["str"]):
            pass
    
        @overload
        def __init__(self, bar: int, qux: Literal["int"]):
            pass
    
        def __init__(self, bar: Bar, qux: Qux):  # type: ignore
            pass