python-3.x - 如何让 mypy 提示将 Any 分配给 int

标签 python-3.x type-hinting mypy typechecking static-typing

mypy --strict 尽职地提示以下代码:

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")

但是下面的代码没有任何错误地被接受:

from typing import Any, Dict

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

if __name__ == "__main__":
    main()

mypy 是否有选项使其也拒绝第二个示例?

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

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 是一个escape hatch,它是您希望类型检查器忽略的变量的注解。这当然不是工会。

来自mypy documentation on Any :

A value with the Any type is dynamically typed. Mypy doesn’t know anything about the possible runtime types of such value. Any operations are permitted on the value, and the operations are only checked at runtime. You can use Any as an “escape hatch” when you can’t use a more precise type for some reason.

(粗体强调我的)

它明确涵盖了您的案例:

Any is compatible with every other type, and vice versa. You can freely assign a value of type Any to a variable with a more precise type:

a: Any = None
s: str = ''
a = 2     # OK (assign "int" to "Any")
s = a     # OK (assign "Any" to "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[],就像您在第三个示例中所做的那样,或者重新考虑您的数据结构以允许更好的类型提示。例如,与其使用具有联合值类型的字典,不如考虑使用具有显式字段和每个字段的特定类型的命名元组或数据类。

关于python-3.x - 如何让 mypy 提示将 Any 分配给 int,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51695484/

相关文章:

python - 如何使用 beautiful soup 来抓取网站来迭代并获取所有值?

python - 变量未记录值的变化

python - Into 和 From 接口(interface) : struggling with typing. 类型的协方差

python - 我如何让 Mypy 意识到 isinstance 已经被调用了?

python - 使用哨兵值作为默认值的类型提示参数

python-3.x - wget 不是内部或外部命令,也不是可运行的程序或批处理文件

python - 无法在同一文件夹中导入模块

python - 可以隐式检查 "zeroness"或 "emptiness"的变量类型

python - “类型”对象在函数定义时不可订阅

python-3.x - mypy可以根据当前对象的类型选择方法返回类型吗?