数据类类型验证程序库
dataclass-type-validator的Python项目详细描述
数据类类型验证程序
dataclass-type-validator
是使用python类型提示信息的dataclasses.dataclass
属性的类型验证库。
安装
pip install dataclass-type-validator
或将dataclass-type-validator
行添加到requirements.txt
一个简单的例子
fromdataclassesimportdataclassfromtypingimportListfromdataclass_type_validatorimportdataclass_type_validatorfromdataclass_type_validatorimportTypeValidationError@dataclass()classUser:id:intname:strfriend_ids:List[int]def__post_init__(self):dataclass_type_validator(self)# Valid UserUser(id=10,name='John Smith',friend_ids=[1,2])# => User(id=10, name='John Smith', friend_ids=[1, 2])# Invalid Usertry:User(id='a',name=['John','Smith'],friend_ids=['a'])exceptTypeValidationErrorase:print(e)# => TypeValidationError: Dataclass Type Validation (errors = {# 'id': "must be an instance of <class 'int'>, but received <class 'str'>",# 'name': "must be an instance of <class 'str'>, but received <class 'list'>",# 'friend_ids': 'must be an instance of typing.List[int], but there are some errors:# ["must be an instance of <class \'int\'>, but received <class \'str\'>"]'})