相关疑难解决方法(0)

Python 中的类型注释是否强制执行静态类型检查?

我正在尝试使用typing模块在用 Python 编写的项目中强制执行一些静态类型检查。

当我定义一个类似于文档中的函数时

def greeting(name: str) -> str:
    return 'Hello ' + name
Run Code Online (Sandbox Code Playgroud)

并尝试做类似的事情greeting(3),我确实收到了以下错误

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 2, in greeting
TypeError: must be str, not int
Run Code Online (Sandbox Code Playgroud)

但是当我再次定义一个名为 test

def test(a: int) -> None:
    print(a)
Run Code Online (Sandbox Code Playgroud)

并且做test("a"),我已经a打印了,没有出现任何错误。我也试过

def test(a: str) -> None:
    print(a)
Run Code Online (Sandbox Code Playgroud)

和 do test(3),但没有引发 TypeError 。

我在完全相同的环境中定义了这两个函数,即使用 iTerm 的交互 python 会话。为什么会发生这种情况?

python static-typing typechecking

1
推荐指数
2
解决办法
956
查看次数

标签 统计

python ×1

static-typing ×1

typechecking ×1