如何在 Python 的命名元组中强制变量类型化?

How to enforce variable typing in Named Tuple in Python?

我正在关注这个 tutorial 关于命名元组的变量类型规范。但是,我修改了代码(如下),即使我输入了错误类型的值,也没有出现错误消息或程序中断。我知道您可以编写自己的 try/except 来引发错误异常,但是是否有现成的 solution/syntax 来强制用户输入正确类型的变量。

from typing import NamedTuple

class Pet(NamedTuple):
    pet_name: str
    pet_type: str

    def __repr__(self):
        return f"{self.pet_name}, {self.pet_type}"

cleons_pet = Pet('Cotton', 'owl')
print('cleons_pet: ', cleons_pet)

cleons_pet_v2 = Pet(222, 1)
print('cleons_pet_v2: ', cleons_pet_v2)

# Output
cleons_pet:  Cotton, owl
cleons_pet_v2:  222, 1
[Finished in 0.1s]

python 中的类型提示不会由 python 本身计算!参见 PEP484

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.

至少有两个项目提供离线类型检查 (mypy and pyre)。如果您在项目中使用类型提示,则绝对应该使用它们。

如果您想在 运行 应用程序时验证输入,您必须通过自己验证数据来说服离线类型检查器,或者使用第三方库。我知道 attrs, where you can use validators or type annotations 用于在线验证。