键入使用Python中Pydantic在JSON文件中解析字符串到范围的注释
我已经设置了一个旨在解析JSON文件的Pydantic类。 range 属性是从“ 11-34”
的字符串中解析的(或更准确地说是从所示的以下等级):
RANGE_STRING_REGEX = r"^(?P<first>[1-6]+)(-(?P<last>[1-6]+))?$"
class RandomTableEvent(BaseModel):
name: str
range: Annotated[str, Field(regex=RANGE_STRING_REGEX)]
@validator("range", allow_reuse=True)
def convert_range_string_to_range(cls, r) -> "range":
match_groups = re.fullmatch(RANGE_STRING_REGEX, r).groupdict()
first = int(match_groups["first"])
last = int(match_groups["last"]) if match_groups["last"] else first
return range(first, last + 1)
生成的模式作品工作和验证通过。
但是, range 属性的类型注释严格来说是不正确的,因为 range 属性从字符串(类型注释)转换为
范围
验证器函数中的对象。
注释它并仍然保持模式一代的正确方法是什么? 是否有另一种处理这种隐式类型转换的方法(例如,将字符串自动转换为Pydantic的INT-自定义类型有类似的东西)吗?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
range
不是pydantic
的支持类型,并且在尝试创建JSON模式时将其用作字段的类型将导致错误,但是Pydantic 支持自定义数据类型:
但是此自定义数据类型不能从
range
继承,因为它是最终的。因此,您可以创建一种自定义数据类型,该类型在内部使用range
并公开范围方法:它将像range
一样工作,但它不会是range(
isInstance(...,range)
将为false
)。相同的
pydantic
文档显示了如何使用__ modify_schema __
方法自定义自定义数据类型的JSON模式。完整示例:
输出:
range
is not a supported type bypydantic
and using it as a type for a field will cause an error when trying to create a JSON schema, butpydantic
supports Custom Data Types:But this custom data type cannot inherit from
range
because it is final. So you could create a custom data type that uses arange
internally and exposes the range methods: it will work like arange
but it will not be arange
(isinstance(..., range)
will beFalse
).The same
pydantic
documentation shows how to use a__modify_schema__
method to customize the JSON schema of a custom data type.Full example:
Output: