python - 字段类型取决于其他字段的类型
问题描述
是否可以创建一个类
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
,但我认为这与此示例无关
解决方案
typing
Python 的系统通常不支持依赖类型。但是,可以模拟某些特定情况。
对于少量的依赖类型,可以列举案例。这需要使各个类型通用:
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
推荐阅读
- laravel - Laravel Livewire 上的 select2 不起作用
- java - “收到空行或输入流结束”是什么意思?
- python - subprocess.communicate() 导致 python 程序在向 minecraft 服务器发送输入时挂起
- sql - 连接在 SQL Server 中使用填充零断开数字
- python - 如何根据条件拆分元组列表?
- json - 如何将varchar插入postgresql json列
- python - How to Get Rid of GPT-2 Warning Message?
- javascript - 如何在反应中将样式添加到正文的一部分
- android - 如何检测最后一次使用 Android 设备的时间?
- r - 尽管使用 GitHub 存储库,但无法为 R 4.0.2 安装吸墨纸或 quantstrat