代码之家  ›  专栏  ›  技术社区  ›  ivaigult

使用pydantic验证递归并集

  •  0
  • ivaigult  · 技术社区  · 3 年前

    请考虑以下列表:

    from pydantic.dataclasses import dataclass
    from typing import Tuple, Union
    
    @dataclass
    class A:
        name: str
        collection: Tuple[Union["A", int], ...]
    
    A.__pydantic_model__.update_forward_refs()
    
    # Does not work:
    c = A("name", (A("a", tuple()), 42,))
    

    当的实例 A 创建,验证失败,出现以下情况:

    pydantic.error_wrappers.ValidationError: 2 validation errors for A
    collection -> 0
      value is not a valid dict (type=type_error.dict)
    collection -> 0
      value is not a valid integer (type=type_error.integer)
    

    这里的问题是 pydantic 不考虑 A. 在验证的实例时为有效项 A. 。例如,如果我删除 A. 项,验证通过得很好:

    # Works fine:
    c = A("name", (42,))
    

    这是个虫子吗?如何使用验证递归并集 pydantic ?

    0 回复  |  直到 3 年前