使用自定义方法验证数据级字段?
在使用Dataclasses时,类型提示很好,但我也寻找的是验证 ,例如最大长度50的字符串,int的int,上限为100, /em>)
无论如何是否有验证传递的值?例如,Pydantic具有这些验证者。我正在寻找本机的东西而不添加外部库。我唯一的解决方案是:
from dataclasses import dataclass
def validate_str(max_length):
def _validate(f):
def wrapper(self, value):
if type(value) is not str:
raise TypeError(f"Expected str, got: {type(value)}")
elif len(value) > max_length:
raise ValueError(
f"Expected string of max length {max_length}, got string of length {len(value)} : {value}" # noqa
)
else:
return f(self, value)
return wrapper
return _validate
@dataclass
class Example:
"""Class for keeping track of an item in inventory."""
@property
def name(self):
return self._name
@name.setter
@validate_str(max_length=50)
def name(self, value):
self._name = value
其中validate_str
只是一种自定义装饰器的方法,可以检查提供的值的长度,但随后我重复了自己。 我想以以下方式以某种方式通过同一行dataclass属性传递验证器
@dataclass
class InventoryItem:
"""Class for keeping track of an item in inventory."""
name: str = validate_somehow()
unit_price: float = validate_somehow()
quantity_on_hand: int = 0
While working with dataclasses, type hints are good but what I'm looking also for is a Validation of passed values (such as string of max length 50, int with upper limit of 100 etc)
Is there anyway to validate passed value ? For example, Pydantic has these Validators. I'm looking for something native without adding external libraries. My only solution is:
from dataclasses import dataclass
def validate_str(max_length):
def _validate(f):
def wrapper(self, value):
if type(value) is not str:
raise TypeError(f"Expected str, got: {type(value)}")
elif len(value) > max_length:
raise ValueError(
f"Expected string of max length {max_length}, got string of length {len(value)} : {value}" # noqa
)
else:
return f(self, value)
return wrapper
return _validate
@dataclass
class Example:
"""Class for keeping track of an item in inventory."""
@property
def name(self):
return self._name
@name.setter
@validate_str(max_length=50)
def name(self, value):
self._name = value
where validate_str
is just a custom decorator method to check length of provided value, but then I repeat myself.
I would like to pass validator somehow in same row of dataclass attribute as:
@dataclass
class InventoryItem:
"""Class for keeping track of an item in inventory."""
name: str = validate_somehow()
unit_price: float = validate_somehow()
quantity_on_hand: int = 0
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
理想的方法是使用
验证器
python Hofth Hof-To Guide 上的示例描述符 。例如:
输出:
The ideal approach would be to use a modified version of the
Validator
example from the Python how-to guide on descriptors.For example:
Output: