【问题标题】:Using mypy to type check and i cant figure out why this errors are happening [closed]使用 mypy 进行类型检查,我无法弄清楚为什么会发生此错误 [关闭]
【发布时间】:2021-08-25 09:10:10
【问题描述】:

所以,我从一开始就使用 mypy 来学习如何使用类型检查在 python 中编码。我正在使用此代码进行训练:

def stars(*args: int, **kwargs: float) -> None:
    
    for arg in args:
        print(arg)
    for key, value in kwargs:
        print(key, value)

stars(1.3,1.3)

我收到此类型错误:

learning_mypy.py:6: error: Unpacking a string is disallowed
learning_mypy.py:7: error: Cannot determine type of 'key'
learning_mypy.py:7: error: Cannot determine type of 'value'
learning_mypy.py:9: error: Argument 1 to "stars" has incompatible type "float"; expected "int"
learning_mypy.py:9: error: Argument 2 to "stars" has incompatible type "float"; expected "int"
Found 5 errors in 1 file (checked 1 source file)  

所以我的问题是:

  • 为什么会出现错误mypy.py:6
  • 如何定义keyvalue 的值类型?
  • 为什么出现错误mypy.py:9

【问题讨论】:

  • star(1.3:1.3) 是无效的语法。你的意思是放别的东西吗?
  • 对不起,是星星(1.3,1.3)

标签: python type-hinting mypy typechecking python-typing


【解决方案1】:

如果您进行以下更改,mypy 不会显示任何内容。

def stars(*args: float, **kwargs: float) -> None:
    
    for arg in args:
        print(arg)
    for key, value in kwargs.items():
        print(key, value)

stars(1.3,1.3)
  • 为什么会出现 mypy.py:6 错误?

    for key, value in kwargs: 对于这一行,您应该将 kwargs 视为 Python 字典。如果您在 for 循环中迭代 kwargs,它将仅迭代字典的键。看下面的代码。

    d = {'1': 'one', '2': 'two', '3': 'three'}
    for key in d:
        print(key)
    

    输出是:

    1
    2
    3
    

    如果您也想打印这些值,可以使用dict.items 方法。

    d = {'1': 'one', '2': 'two', '3': 'three'}
    for key, value in d.items():
        print(key, value)
    

    输出是:

    1 one
    2 two
    3 three
    

    或者,您可以通过字典访问键的值。

    for key in d:
        print(key, d[key])
    

    在第 6 行,因为只生成了密钥,而且密钥也是 str;您正在尝试解压缩字符串。考虑下面的代码:

    var1, var2 = "test_variable"
    

    这正是你的第二个 for 循环所做的。

  • 如何定义 key 和 value 的类型?

    您无法为kwargs 定义键的类型,但您可以定义值的类型。 (你已经完成了:kwargs: float

  • 为什么错误 mypy.py:9 正在发生?

    您将*args 定义为int。但是你通过了float。 如果你更改*args: float,这个错误就会消失。

【讨论】:

  • 很好的答案@ErdogonOnal!大约一个月前,我开始了学习 python 的旅程,几天前我发现了静态类型和类型检查。您认为是从一开始就开发的好习惯,还是随着我的语言知识更加成熟而开始使用?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-07-31
  • 2017-06-15
  • 2023-02-11
  • 1970-01-01
  • 1970-01-01
  • 2020-11-23
相关资源
最近更新 更多