python - Mypy:键入要加在一起的两个 int 或 str 列表

标签 python mypy python-typing

我有一个函数可以合并两个 int 或 str 列表。 不能出现两个列表属于不同类型的情况。

它由以下代码定义:

AddableList = ...


def add_arrays(array: AddableList, array2: AddableList) -> AddableList:
    if len(array) != len(array2):
        raise ValueError

    return [a + b for a, b in zip(array, array2)]

当键入 AddableList 时,使用 List[int] mypy:成功:没有问题

当键入 AddableList 时,使用 List[str] mypy:成功:没有问题

但是mypy会返回如下错误

error: Unsupported operand types for + ("int" and "str")
error: Unsupported operand types for + ("str" and "int")
note: Both left and right operands are unions
Found 2 errors in 1 file (checked 333 source files)

当使用 AddableList = List[Union[int, str]] 正确输入列表时

最后,当尝试将 AddableList 键入 Union[List[int], List[str]] 时,mypy 错误:

error: Unsupported left operand type for + ("object")

我应该使用什么类型来解决这个问题?

最佳答案

使用 TypeVar 将解析为一种类型或另一种类型(但不能在同一上下文中同时解析两种类型):

from typing import List, TypeVar

Addable = TypeVar("Addable", str, int)


def add_arrays(array: List[Addable], array2: List[Addable]) -> List[Addable]:
    if len(array) != len(array2):
        raise ValueError

    return [a + b for a, b in zip(array, array2)]

reveal_type(add_arrays([1, 2, 3], [2, 3, 4]))    # List[int]
reveal_type(add_arrays(["a", "b"], ["c", "d"]))  # List[str]
reveal_type(add_arrays([1, 2, 3], ["a", "b", "c"]))  # error

最后一行抛出错误,因为没有 Addable 可以解析为的类型:

test.py:14: error: Cannot infer type argument 1 of "add_arrays"

关于python - Mypy:键入要加在一起的两个 int 或 str 列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72419940/

相关文章:

python - 如何在不丢失有效数字的情况下转换 str 中的 float ?

python-3.x - Mypy 在类型分支时错误地报告联合类型变量的错误

python - 从另一个函数复制类型签名

python-3.x - 让 mypy 警告不同类型变量的相等性检查

python - 子类中返回值的类型提示

python - 预期类型 'List[A]'(匹配泛型类型 'List[_T]' ),在正确键入的列表中得到 'List[B]'

php - Odoo 服务器超时和内存限制

python - 在 Python 2.7 和 OpenCV 3.3 中使用 triangulatePoints 每次输出 3D 点都会发生变化

python - 如何在复杂的pandas groupby中绘制图表?

对 NamedTuple 的 Python 类型支持