首页 > 解决方案 > 字段类型取决于其他字段的类型

问题描述

是否可以创建一个类

from typing import Union, Literal

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

这样,如果quxLiteral["str"],那么bar是类型str,如果quxLiteral["int"],那么bar是类型int?可以注释掉吗?

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

标签: pythontype-hintingmypypython-typing

解决方案


typingPython 的系统通常不支持依赖类型。但是,可以模拟某些特定情况。

对于少量的依赖类型,可以列举案例。这需要使各个类型通用:

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
    

推荐阅读