扩展其他类以通过注释进行类型检查
TypedClass的Python项目详细描述
类型类
一个python类,用于扩展其他类,让它们对带注释的属性进行类型检查,以及其他一些好的东西,如必需的属性、不可变的属性、属性的验证函数、属性的选择
示例用法
类型类
fromTypedClassimportTypedClass,TypeDefclassExampleTypedClass(TypedClass):simple:intusing_type_def:TypeDef(typeof=int)simple_with_default:float=1.01type_hint_with_default:TypeDef(typeof=int)=22all_options:TypeDef(typeof=int,required=True,immutable=True,choices=[21,22,23],validate_fn=lambdax:x>20)=23def__init__(self,simple:int,using_type_def:int,simple_with_default:float=1.01,type_hint_with_default:int=22,all_options:int=23,):super().__init__(simple=simple,using_type_def=using_type_def,simple_with_default=simple_with_default,type_hint_with_default=type_hint_with_default,all_options=all_options)
类型dclassstrict
与上面一样,默认情况下,只有所有内容都设置为必需和不可变。
类型DClassJSON
fromTypedClassimportTypedClassJsonclassExampleJSONValidationUsageObj(TypedClassJson):name:strvalue:strvalid:boolclassExampleJSONValidationUsageWithHelperClass(TypedClassJson):_id:intsender:strkind:strnested_obj:ExampleJSONValidationUsageObjnested_obj_with_help:ExampleJSONValidationUsageObjexample_json={'_id':1,'sender':'nic','kind':'message','nested_obj':{'name':'nested_obj','value':'cool','valid':True},'nested_obj_with_help':{'name':'nested_obj_with_help','value':'very cool','valid':True}}# ...importunittestjson_output_example=ExampleJSONValidationUsageWithHelperClass(example_json)tc=unittest.TestCase('__init__')tc.assertEqual(example_json,json_output_example.dict)