Python 静态类型不起作用

Python static typing does not work

我发现 Python 打算支持静态类型,但它仍处于测试阶段。 我用 python 3.4.3 尝试了以下代码:

def somme(a: int, b: int) -> int:
    return a + b

支持语法,但没有得到预期的结果。如果我输入 somme('1', '3') 我得到 13,而我应该得到 TypeError 异常说 int variable expected.

有没有人知道为什么它不起作用?

里面的函数注解只有注解,仅此而已。它们是有关预期用途的文档。正如 PEP 3107 中所说,该机制提供了一种单一的标准方法来指定函数参数和 return 值,取代了各种临时工具和库。

但正如它继续说的那样:

Function annotations are nothing more than a way of associating arbitrary Python expressions with various parts of a function at compile-time.

By itself, Python does not attach any particular meaning or significance to annotations. Left to its own, Python simply makes these expressions available as described in Accessing Function Annotations below.

PEP 484 添加了更多使用这些注释来标记类型的约定和工具,在 Python 3.5 中采用。但是语言本身仍然没有运行时间检查:它"includes support for off-line type checkers such as mypy"。

也就是说,使用这些注解后,您可以运行第三方类型检查器来检查您的代码是否符合注解的类型。将这些注释构建到语言中应该可以使各种 IDE 更容易提供此服务。

实际上,您不应该在此处使用静态类型。您编写的代码实际上是一种简单的文档形式,"type hinting",如 here 所述。引用该 PEP:

While these annotations are available at runtime through the usual annotations attribute, no type checking happens at runtime . Instead, the proposal assumes the existence of a separate off-line type checker which users can run over their source code voluntarily. Essentially, such a type checker acts as a very powerful linter. (While it would of course be possible for individual users to employ a similar checker at run time for Design By Contract enforcement or JIT optimization, those tools are not yet as mature.)

换句话说,它的开发是为了支持第三方库,该库实际上会为您进行检查。我从来没有为 Python 中的静态类型而烦恼,尽管我的一个朋友经常使用 MyPy 来实现它。这可能就是您要找的。

编辑:

安装: MyPy可以使用pip安装:

pip install mypy-lang

用法:您可以按如下方式对您的程序进行类型检查:

~$ mypy my_script.py