使用键入创建 NamedTuple 时引发 TypeError

Raising TypeError when creating a NamedTuple with typing

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

from typing import NamedTuple

class Foo(NamedTuple):

    bar : int     
    sla : str

然而,当我尝试使用无效类型创建 namedtuple 的实例时,没有引发异常

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

#i can even print it

print(test.bar)
´´´

typing 模块实现类型提示,如 PEP 484 中所定义。类型提示正是名称所暗示的......它们是 "hints"。它们本身不会影响 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 将你传递给构造函数的字符串参数标记为违反了类型提示,声明: "Expected type 'int', got 'str' instead"。所以 PyCharm IDE 就是这样一种使用类型提示的工具。然而,PyCharm 对 运行 代码非常满意并且没有生成任何错误。

from typing import NamedTuple


class Foo(NamedTuple):
    bar: int
    sla: str

    def check_type(self):
        for field, field_type in self._field_types.items():
            if not isinstance(getattr(self, field), field_type):
                raise TypeError('{} must be {}'.format(field, field_type))
        return self


if __name__ == '__main__':
    test = Foo('not an int', 3).check_type()
    print(test.bar)

您可以添加一个额外的方法来检查。上面的代码将在不匹配时引发 TypeError。