使用 mypy 进行类型检查,但我无法弄清楚为什么会发生此错误

Using mypy to type check and i cant figure out why this errors are happening

所以,我使用 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 不会显示任何内容。

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 循环所做的。

  • 如何定义键和值的类型?

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

  • 为什么错误 mypy.py:9 正在恶化?

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