python - 通过键入创建 NamedTuple 时引发 TypeError

标签 python typing namedtuple

如何使我的命名元组引发 TypeError 异常?

from typing import NamedTuple

class Foo(NamedTuple):

    bar : int     
    sla : str

但是,当我尝试使用无效类型创建命名元组的实例时,不会引发异常

test = Foo('not an int',3)

#i can even print it

print(test.bar)
´´´

最佳答案

typing 模块实现类型提示,如 PEP 484 中所定义。 。类型提示正如其名称所暗示的那样......它们是“提示”。它们本身不会影响 Python 代码的执行。根据 PEP 484 文档:

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.

因此,您需要一些额外的代码或工具来利用添加到代码中的类型信息,以提前告诉您代码违反了类型提示,或者在代码运行时告诉您。 typing 模块本身不提供此功能。

我将您的代码放入 PyCharm IDE 中,IDE 将您传递给构造函数的字符串参数标记为违反类型提示,并指出:“预期类型 'int',得到 'str'相反”。 PyCharm IDE 就是这样一种利用类型提示的工具。然而,PyCharm 很高兴运行代码并且没有生成任何错误。

关于python - 通过键入创建 NamedTuple 时引发 TypeError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55859823/

相关文章:

python - 在最大时间限制的循环中运行外部程序

optimization - 弱类型会提高性能还是降低性能?

java - 链接方法时不能依赖目标类型

Python 命名元组切片

python - 要列出的命名元组字符串

python - NamedTuples、Hashable 和 Python

python - Pytorch 运行时错误 : size mismatch, m1 : [1 x 7744], m2:[400 x 120]

python - 如何使用在每一行和每一列调用的函数有效地填充 numpy ndarray?

python - 将图像添加到 Tkinter Entry

javascript - 泛型错误,类型 T 上不存在变量名