簡體   English   中英

mypy:無法推斷“map”的類型參數 1

[英]mypy: Cannot infer type argument 1 of "map"

嘗試使用 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: 錯誤:無法推斷“map”的類型參數 1

為什么會出現這個錯誤? 我該如何解決?

謝謝:)

編輯:這實際上是 mypy 中的一個錯誤,現在已修復。

您可能已經知道, mypy依賴於typeshed來存根 Python 標准庫中的類和函數。 我相信您的問題與 typeshed 的map存根有關

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

並且 mypy 的當前狀態是它的類型推斷不是無限的。 (該項目還有600 多個未解決的問題。

我相信您的問題可能與問題 #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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM