【问题标题】:Conditional types with mypy带有 mypy 的条件类型
【发布时间】:2022-10-17 18:00:35
【问题描述】:

我有以下代码sn-p:

from typing import TypedDict

class Super(TypedDict):
    foo: int

class SubA(Super):
    bar: int

class SubB(Super):
    zap: int

def print_props(inp: Super, key: str):
    print(inp[key])

当我使用SubASubB 的实例调用print_props 方法时,它是有效的,因为它们是Super 的子类型。

但是mypy 会抱怨参数key,因为它必须是文字"foo"。 是否可以给mypy 提示,以便它能够确定哪些键是有效的? 例如:“当使用SubB 的实例调用print_props 时,只有"foo""zap" 有效。”

我看了一下generics;我认为可以声明一个仅限于Super 的子类型的类型变量,但是是否可以表达类型变量的具体类型(SubASubB)与文字值之间的依赖关系那么 key 应该被限制在什么地方?

【问题讨论】:

  • 不过,SubASubB 不是 Super 的子类型。它们是TypedDict 的子类。

标签: python mypy python-typing strong-typing


【解决方案1】:

Literal 的重载可以很好地做到这一点,尽管我想知道不同的设计是否会更好。我有点担心在 SO 答案中越来越频繁地使用 overloadLiteral。他们都向我暗示了设计的味道

@overload
def printMyProps(input: SubA, key: Literal["foo", "bar"]) -> None: ...

@overload
def printMyProps(input: SubB, key: Literal["foo", "zap"]) -> None: ...

def printMyProps(input: SubA | SubB, key: Literal["foo", "bar", "zap"]) -> None:
  print(input[key])  # type: ignore

我使用了type: ignore,因为它是一个简短的函数,我不能在TypedDict 上使用isinstance。 TBH overload 实现通常需要类型修改。 API 按预期工作

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-11-09
    • 2022-06-23
    • 1970-01-01
    • 1970-01-01
    • 2020-05-31
    • 1970-01-01
    相关资源
    最近更新 更多