gpt4 book ai didi

python - mypy:无法推断 "map"的类型参数 1

转载 作者:太空宇宙 更新时间:2023-11-03 15:53:36 29 4
gpt4 key购买 nike

当尝试使用 mypy 检查以下代码时:

import itertools
from typing import Sequence, Union, List

DigitsSequence = Union[str, Sequence[Union[str, int]]]


def normalize_input(digits: DigitsSequence) -> List[str]:
try:
new_digits = list(map(str, digits)) # <- Line 17
if not all(map(str.isdecimal, new_digits)):
raise TypeError
except TypeError:
print("Digits must be an iterable containing strings.")
return []
return new_digits

mypy 抛出以下错误:

calculate.py:17: error: Cannot infer type argument 1 of "map"

为什么会出现这个错误?我该如何解决?

谢谢:)

编辑它实际上是一个bug在 mypy 中,现在已修复。

最佳答案

您可能已经知道,mypy取决于 typeshed stub Python 标准库中的类和函数。我相信您的问题与 typeshed 的 stubbing of map 有关:

@overload
def map(func: Callable[[_T1], _S], iter1: Iterable[_T1]) -> Iterator[_S]: ...

而且 mypy 的当前状态是它的类型推断不是无限的。 (项目还有over 600 open issues.)

我相信您的问题可能与 issue #1855 有关.我相信情况确实如此,因为 DigitsSequence = strDigitsSequence = Sequence[int] 都有效,而 DigitsSequence = Union[str, Sequence[int]] 没有。

一些解决方法:

  1. 改用 lambda 表达式:

    new_digits = list(map(lambda s: str(s), digits))
  2. 重新转换为一个新变量:

    any_digits = digits # type: Any
    new_digits = list(map(str, any_digits))
  3. 要求 mypy 忽略该行:

    new_digits = list(map(str, digits)) # type: ignore

关于python - mypy:无法推断 "map"的类型参数 1,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44988144/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com