Python 使用键入创建NamedTuple时引发TypeError
如何使命名元组引发TypeError异常Python 使用键入创建NamedTuple时引发TypeError,python,typing,namedtuple,Python,Typing,Namedtuple,如何使命名元组引发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) ´´´ 键入模块实现类型提示,如中所定义。类型提示正是名称所暗示的…它们
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)
´´´
键入
模块实现类型提示,如中所定义。类型提示正是名称所暗示的…它们是“提示”。它们本身不会影响Python代码的执行。根据PEP 484文件:
虽然这些注释在运行时通过通常的
注释属性,运行时不进行类型检查。相反,该提案假设存在一个单独的离线系统
类型检查器,用户可以自动运行其源代码。
本质上,这样的类型检查器充当非常强大的过梁
因此,您需要一些额外的代码或工具来利用添加到代码中的类型信息,以便事先告诉您的代码违反了类型提示,或者在代码运行时告诉您。输入
模块本身不提供此功能
我将您的代码放在我的PyCharm IDE中,IDE将您传递给构造函数的字符串参数标记为违反类型提示,声明:“预期类型为'int',改为'str'”。因此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