标量类型检查在 python 中不起作用

问题描述

标量类型检查在 Python (v 3.8.6) 中不起作用。

def test(x: int) -> int:
    print(type(x))
    return x

a = test('a')

没有 int 作为输入参数根本没有关系。它也不表示 int 不是输出参数。

输出

<class 'str'>

我希望 ValueError!

解决方法

你说的是函数注解

def test(x: int) -> int

这意味着该函数应采用 int 参数,并且还应具有 int 返回值。这些是可选的,不是由 Python 强制执行的,但它们对静态类型分析工具很有用,并有助于 IDE 完成代码完成和重构。

在此处阅读更多信息:https://docs.python.org/3/glossary.html#term-function-annotation