在pydantic.validators.find_validators typeError:issubclass()arg 1必须是类

发布于 2025-01-20 09:25:33 字数 1078 浏览 1 评论 0原文

您好,我正在阅读带有以下格式的JSON:

{
    "1": {"id":1, "type": "a"},
    2: {"id":2, "type": "b"},
    "3": {"id":3, "type": "c"},
    "5": {"id":4, "type": "d"}
}

您可以看到密钥是数字,但不是仪表仪。

因此,我有以下baseModel嵌套dict

@validate_arguments
class ObjI(BaseModel):
    id: int
    type: str

问题是如何验证dict> dict中的所有项目是obji无需使用:

objIs = json.load(open(path))
assert type(objIs) == dict
    for objI in objIs.values():
        assert type(objI) == dict
        ObjI(**pair)

我尝试:

@validate_arguments
class ObjIs(BaseModel):
    ObjIs:  Dict[Union[str, int], ObjI]

编辑

错误验证上一个的错误是:

in pydantic.validators.find_validators TypeError: issubclass() arg 1 must be a class

这可能吗?

谢谢

Hello I am reading a JSON with the following format:

{
    "1": {"id":1, "type": "a"},
    2: {"id":2, "type": "b"},
    "3": {"id":3, "type": "c"},
    "5": {"id":4, "type": "d"}
}

As you can see the keys are numbers but are not consecutives.

So I have the following BaseModel to the nested dict:

@validate_arguments
class ObjI(BaseModel):
    id: int
    type: str

The question is how can I validate that all items in the dict are ObjI without use of:

objIs = json.load(open(path))
assert type(objIs) == dict
    for objI in objIs.values():
        assert type(objI) == dict
        ObjI(**pair)

I tried with:

@validate_arguments
class ObjIs(BaseModel):
    ObjIs:  Dict[Union[str, int], ObjI]

EDIT

The error validating the previous is:

in pydantic.validators.find_validators TypeError: issubclass() arg 1 must be a class

Is this possible?

Thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

与之呼应 2025-01-27 09:25:33

您可以更改模型定义以使用自定义根类型(不需要 validate_arguments 装饰器):

from pydantic import BaseModel
from typing import Dict

class ObjI(BaseModel):
    id: int
    type: str

class ObjIs(BaseModel):
    __root__: dict[int, ObjI]

现在可以使用 JSON 数据初始化模型,例如:

import json
with open("/path/to/data") as file:
    data = json.load(file)

objis = ObjIs.parse_obj(data)

如果 data 包含无效的内容类型(或缺少字段),prase_obj() 将引发 ValidationError
例如,如果 data 看起来像这样:

data = {
    "1": {"id": "x", "type": "a"},
#                ^
#                wrong type
    2: {"id": 2, "type": "b"},
    "3": {"id": 3, "type": "c"},
    "4": {"id": 4, "type": "d"},
}

objs = ObjIs.parse_obj(data)

它将导致:

pydantic.error_wrappers.ValidationError: 1 validation error for ObjIs
__root__ -> 1 -> id
  value is not a valid integer (type=type_error.integer)

这告诉我们具有键 1 的对象的 id 具有无效的类型。

(您可以像 Python 中的任何其他异常一样捕获并处理 ValidationError。)

(pydantic docs 还建议在模型上实现自定义 __iter____getitem__ 方法(如果您想访问中的项目)直接输入 __root__ 字段。)

You could change your model definitions to use a custom root type (no need for the validate_arguments decorators):

from pydantic import BaseModel
from typing import Dict

class ObjI(BaseModel):
    id: int
    type: str

class ObjIs(BaseModel):
    __root__: dict[int, ObjI]

The model can now be initialised with the JSON data, e.g. like this:

import json
with open("/path/to/data") as file:
    data = json.load(file)

objis = ObjIs.parse_obj(data)

If data contains invalid types (or has missing fields), prase_obj() will raise a ValidationError.
For examples, if data looked like this:

data = {
    "1": {"id": "x", "type": "a"},
#                ^
#                wrong type
    2: {"id": 2, "type": "b"},
    "3": {"id": 3, "type": "c"},
    "4": {"id": 4, "type": "d"},
}

objs = ObjIs.parse_obj(data)

it would result in:

pydantic.error_wrappers.ValidationError: 1 validation error for ObjIs
__root__ -> 1 -> id
  value is not a valid integer (type=type_error.integer)

which tells us that the id of the object with key 1 has an invalid type.

(You can catch and handle a ValidationError like any other exception in Python.)

(The pydantic docs also recommend to implement custom __iter__ and __getitem__ methods on the model if you want to access the items in the __root__ field directly.)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文