本文介绍了如何让Mypy抱怨将一个Any分配给一个int的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

mypy --strict忠实地抱怨以下代码:

mypy --strict dutifully complains about the following code:

from typing import Any, Dict

def main() -> None:
    my_str: str = 'hello'
    my_int: int = my_str

if __name__ == "__main__":
    main()

通过输出:

error: Incompatible types in assignment (expression has type "str", variable has type "int")

但是接受以下代码而没有任何错误:

However the following code is accepted without any error:

from typing import Any, Dict

def main() -> None:
    my_str: Any = 'hello'
    my_int: int = my_str

if __name__ == "__main__":
    main()

mypy是否可以拒绝第二个示例?

Is there an option for mypy to make it also reject the second example?

我希望它会这样做,因为它还会拒绝以下内容:

I expect it to do so, because it also rejects the following:

from typing import Any, Dict, Union

def main() -> None:
    my_str: Union[int, str] = 'hello'
    my_int: int = my_str

if __name__ == "__main__":
    main()

具有:

error: Incompatible types in assignment (expression has type "Union[int, str]", variable has type "int")

据我所知,Any只是所有可能类型的Union.

And in my understanding an Any is just the Union of all possible types.

推荐答案

那是不正确的. Any转义阴影线,是您要类型检查器忽略的变量的注释.当然不是工会.

That's not correct. Any is an escape hatch, an annotation for variables that you want the type checker to ignore. It certainly is not a union.

来自Any mypy文档:

(加粗强调我的意思)

它明确涵盖了您的情况:

It explicitly covers your case:

a: Any = None
s: str = ''
a = 2     # OK (assign "int" to "Any")
s = a     # OK (assign "Any" to "str")

声明的(和推断的)类型在运行时被忽略(或擦除).它们基本上被视为注释,因此,即使程序运行时s获得int值,而s的声明类型实际上是str,以上代码也不会生成运行时错误!

Declared (and inferred) types are ignored (or erased) at runtime. They are basically treated as comments, and thus the above code does not generate a runtime error, even though s gets an int value when the program is run, while the declared type of s is actually str!

因此,如果您希望类型检查器继续跟踪值的使用方式,则正确的方法是不使用Any .就像在第三个示例中一样,使用Union[],或者重新考虑数据结构以提供更好的类型提示.例如,不要使用具有联合值类型的字典,而应考虑使用具有显式字段和每个字段特定类型的命名元组或数据类.

So the correct approach is to not use Any if you want the type checker to keep tracking how the value is used. Use a Union[], as you did in your third example, or re-think your data structures to allow for better type hinting. For example, rather than use a dictionary with a union value type, consider using a named tuple or dataclass with explicit fields and a specific type for each field.

这篇关于如何让Mypy抱怨将一个Any分配给一个int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-12 07:05