Python3.7在一段时间前发布了,我想测试一些奇特的新dataclass
+类型特性。对于本机类型和来自typing
模块的提示,获取正确的提示非常简单:
>>> import dataclasses
>>> import typing as ty
>>>
... @dataclasses.dataclass
... class Structure:
... a_str: str
... a_str_list: ty.List[str]
...
>>> my_struct = Structure(a_str='test', a_str_list=['t', 'e', 's', 't'])
>>> my_struct.a_str_list[0]. # IDE suggests all the string methods :)
但我想尝试的另一件事是在运行时强制类型提示作为条件,即不可能存在类型不正确的dataclass
。它可以用__post_init__
很好地实现
>>> @dataclasses.dataclass
... class Structure:
... a_str: str
... a_str_list: ty.List[str]
...
... def validate(self):
... ret = True
... for field_name, field_def in self.__dataclass_fields__.items():
... actual_type = type(getattr(self, field_name))
... if actual_type != field_def.type:
... print(f"\t{field_name}: '{actual_type}' instead of '{field_def.type}'")
... ret = False
... return ret
...
... def __post_init__(self):
... if not self.validate():
... raise ValueError('Wrong types')
这种validate
函数适用于本机类型和自定义类,但不适用于typing
模块指定的那些类型:
>>> my_struct = Structure(a_str='test', a_str_list=['t', 'e', 's', 't'])
Traceback (most recent call last):
a_str_list: '<class 'list'>' instead of 'typing.List[str]'
ValueError: Wrong types
有没有更好的方法来用typing
-typed列表验证无类型列表?最好不包括检查任何list
、dict
、tuple
或set
中作为dataclass
‘属性的所有元素的类型。
发布于 2019-04-30 05:21:53
我刚刚发现了这个问题。
pydantic可以对数据类进行开箱即用的全类型验证。(承认:我创建了pydantic)
只需使用pydantic版本的装饰器,结果数据类就完全是普通的了。
from datetime import datetime
from pydantic.dataclasses import dataclass
@dataclass
class User:
id: int
name: str = 'John Doe'
signup_ts: datetime = None
print(User(id=42, signup_ts='2032-06-21T12:00'))
"""
User(id=42, name='John Doe', signup_ts=datetime.datetime(2032, 6, 21, 12, 0))
"""
User(id='not int', signup_ts='2032-06-21T12:00')
最后一行将给出:
...
pydantic.error_wrappers.ValidationError: 1 validation error
id
value is not a valid integer (type=type_error.integer)
发布于 2021-02-03 23:03:11
为此,我创建了一个小型Python库:https://github.com/tamuhey/dataclass_utils
这个库可以应用于包含另一个数据类(嵌套数据类)和嵌套容器类型(如Tuple[List[Dict...
)的数据类
发布于 2020-05-03 16:04:26
对于键入别名,必须单独检查注释。我喜欢这样:https://github.com/EvgeniyBurdin/validated_dc
https://stackoverflow.com/questions/50563546
复制相似问题