我想从实例创建起就验证类型是否正确,我尝试使用@dataclass
装饰器,但不允许我使用__init__
方法,我也尝试使用自定义类类型的自定义项
也按照类型的顺序进行了一些验证(例如,如果是int
,则表示field>0
或如果是str
干净空格),我可以使用字典来验证类型,但是我想知道是否有一种方法可以用pythonic的方式进行]
class Car(object):
""" My class with many fields """
color: str
name: str
wheels: int
def __init__(self):
""" Get the type of fields and validate """
pass
from dataclasses import dataclass, fields
def validate(instance):
for field in fields(instance):
attr = getattr(instance, field.name)
if not isinstance(attr, field.type):
msg = "Field {0.name} is of type {1}, should be {0.type}".format(field, type(attr))
raise ValueError(msg)
@dataclass
class Car:
color: str
name: str
wheels: int
def __post_init__(self):
validate(self)
的替代方法是使用@dataclass
。它提供了开箱即用的验证和转换,并且直接在字段级别完成,因此您可以在任何类中使用pyfields
,而无需以任何方式对其进行修改。
pyfields
产生以下两个错误
field
和
from pyfields import field, init_fields
from valid8.validation_lib import is_in
ALLOWED_COLORS = ('blue', 'yellow', 'brown')
class Car(object):
""" My class with many fields """
color: str = field(check_type=True, validators=is_in(ALLOWED_COLORS))
name: str = field(check_type=True, validators={'should be non-empty': lambda s: len(s) > 0})
wheels: int = field(check_type=True, validators={'should be positive': lambda x: x > 0})
@init_fields
def __init__(self, msg="hello world!"):
print(msg)
c = Car(color='blue', name='roadie', wheels=3)
c.wheels = 'hello' # <-- (1) type validation error, see below
c.wheels = 0 # <-- (2) value validation error, see below
有关详细信息,请参见TypeError: Invalid value type provided for '<...>.Car.wheels'.
Value should be of type <class 'int'>. Instead, received a 'str': 'hello'
。我是作者:)