【问题标题】:mypy incompatible types list<nothing> has the type list<str>mypy 不兼容类型 list<nothing> 的类型为 list<str>
【发布时间】:2022-01-09 19:23:54
【问题描述】:

我正在使用带有代码的 prompt-toolkit python 库:

from __future__ import annotations
from prompt_toolkit.shortcuts import checkboxlist_dialog

results: list[str] = checkboxlist_dialog(
    title="CheckboxList dialog",
    text="What would you like in your breakfast ?",
    values=[
        ("eggs", "Eggs"),
        ("bacon", "Bacon"),
        ("croissants", "20 Croissants"),
        ("daily", "The breakfast of the day"),
    ],
).run()

当我运行 mypy 0.931 时,我得到:

test.py:4: error: Incompatible types in assignment (expression has type "List[<nothing>]", variable has type "List[str]")
test.py:4: note: "List" is invariant -- see https://mypy.readthedocs.io/en/stable/common_issues.html#variance
test.py:4: note: Consider using "Sequence" instead, which is covariant
test.py:7: error: Argument "values" to "checkboxlist_dialog" has incompatible type "List[Tuple[str, str]]"; expected "Optional[List[Tuple[<nothing>, Union[str, MagicFormattedText, List[Union[Tuple[str, str], Tuple[str, str, Callable[[MouseEvent], None]]]], Callable[[], Any], None]]]]"

我不确定问题是否出在我的代码上,因为返回值类似于['eggs', 'bacon'],即list[str]。 mypy 的这个错误也很奇怪,因为我认为我不应该在这里使用协变。关于可能是什么问题的任何提示?

【问题讨论】:

  • 你问的是第一条还是第二条错误信息?
  • 其实是第一个,但两者都有关系。如果将 # type: ignore 添加到值中。它没有显示任何消息。

标签: python type-hinting mypy type-annotation prompt-toolkit


【解决方案1】:

我认为问题在于 mypy 关于checkboxlist_dialog 函数的信息非常少,当然也不知道它的返回类型可以从value 参数中得出。

你可能不得不写:

from typing import cast

results = cast(list[string], checkboxlist_dialog(....))

它告诉 mypy 你知道你在做什么,返回类型真的是list[string],不管它怎么想。

【讨论】:

  • 没有信息的mypy不会抱怨错误的类型。我已经检查了github.com/prompt-toolkit/python-prompt-toolkit/blob/master/… 和类型似乎没问题,所以要更好地理解这一点,需要更强大的 mypy 知识。
  • 我同意你的看法。如果 mypy 实际上正在读取该文件(而不是库存根),那么它应该能够确定 _T 是一个字符串。但事实并非如此。您必须决定在尝试调试 mypy 或继续执行程序的其余部分时是否值得。有时 mypy 很有帮助。有时您必须面对这样一个事实,即它仍在进行中且并不完美。
  • @FrankYellin 你认为这是来自 mypy 0.931 的错误吗?使用您的解决方案并停止忽略类型,我仍然会遇到第二个错误,这很烦人,因为它是 prompt-toolkit 文档中的示例。
  • 我没有注意到第二条错误消息。 mypy 真的不想绑定_T,是吗。作为最后一点绝望,也许尝试拉动values 参数并将其放入变量中。甚至可能告诉 mypy 变量是list[tuple[str, str]] 类型。同样,当 mypy 明显(我认为)错误时,你想花多少时间与它作斗争,这取决于你。
猜你喜欢
  • 2021-10-18
  • 1970-01-01
  • 2021-09-26
  • 1970-01-01
  • 1970-01-01
  • 2022-06-14
  • 1970-01-01
  • 2014-09-07
  • 2020-02-10
相关资源
最近更新 更多