【问题标题】:Get Mypy to accept unpacked dict让 Mypy 接受解压的字典
【发布时间】:2018-05-17 20:17:41
【问题描述】:

我的 mypy 有问题

我有这样的代码:

func(arg1, arg2, arg3=0.0, arg4=0.0)
# type: (float, float, float, float) -> float
# do something and return float.

dict_with_other_arguments = {arg3: 0.5, arg4: 1.4}
a = func(arg1, arg2, **dict_with_other_arguments)

问题是 mypy 不检查字典中的类型,而是出现如下错误: 错误:“func”的参数 3 具有不兼容的类型“**Dict[str, float]”;预期“浮动”

任何想法如何在不更改代码的情况下解决此问题?

【问题讨论】:

  • 您能否更新您的帖子,使其包含您的问题的minimal, complete, and verifiable example
  • 当然,编辑得更清楚了。
  • 我无法重现您的问题,抱歉。例如,Mypy 对 this program 非常满意。 (请注意,我稍微调整了您的示例以确保一切都可以在运行时实际工作)。
  • @Michael0x2a 我提供了here 问题的示例,它似乎在涉及多种类型时发生。
  • 是的,这可能是问题所在。

标签: python dictionary mypy


【解决方案1】:

Mypy 在标记您的函数调用方面是正确的。以下代码说明了原因:

def func(str_arg='x', float_arg=3.0):
  # type: (str, float) -> None
  print(str_arg, float_arg)

kwargs1 = {'float_arg': 8.0}
kwargs2 = {'str_arg': 13.0}  # whoops

func(float_arg=5.0)  # prints "x 5.0" -- good
func(**kwargs1)      # prints "x 13.0" -- good but flagged by Mypy
func(**kwargs2)      # prints "13.0 3.0" -- bad

在本例中,kwargs1kwargs2 都是 Dict[str, float] 类型。类型检查器不考虑键的内容,只考虑它们的类型,因此对func 的第二次和第三次调用看起来与 Mypy 相同。它们必须要么都是错误,要么都可以接受,而且它们不能都可以接受,因为第三次调用违反了类型系统。

类型检查器可以确保您没有在 dict 中传递错误类型的唯一方法是,所有未显式传递的参数是否共享 dict 值的类型。但是请注意,mypy 不会保护您免受因在 dict 中重新指定关键字参数而导致的错误:

# This works fine:
func('x', **kwargs1)
# This is technically type safe and accepted by mypy, but at runtime raises
# `TypeError: func() got multiple values for argument 'str_arg'`:
func('x', **kwargs2)

这里有一些关于这个问题的进一步讨论:https://github.com/python/mypy/issues/1969

【讨论】:

    猜你喜欢
    • 2018-11-03
    • 2011-11-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多