如何使我的命名元组引发 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/