用pydantic验证类(Hydra-Core列表)

发布于 2025-01-25 21:38:52 字数 2295 浏览 4 评论 0原文

1。上下文

如何验证pydantic的特定类别?

我正在使用 pydantic verate yaml列表参数由 hydra ,以后将其传递给建模例程。问题在于,Hydra字典不包含值列表,而是包含这些值的类。如何验证这些参数?

2。示例

在以下示例中,有2个文件:

  • cfg.yaml包含要验证的参数
  • main.py.py.py.py包含加载和验证cfg的指令.yaml

2.1配置文件cfg.yaml

params_list:
  - 10
  - 0
  - 20

2.2解析器/验证器文件main.py.py

import hydra
import pydantic
from omegaconf import DictConfig, OmegaConf
from typing import List

class Test(pydantic.BaseModel):
    params_list: List[int]

@hydra.main(config_path=".", config_name="cfg.yaml")
def go(cfg: DictConfig):
    parsed_cfg = Test(**cfg)
    print(parsed_cfg)

if __name__ == "__main__":
    go()

问题

3。执行时 python3 main.py.py出现以下错误

值不是有效列表(type = type_error.list)

这是因为Hydra具有用于处理列表的特定类,称为Omegaconf.listConfig.listConfig.listConfig,可以通过

print(type(cfg['params_list']))

在<<<<<代码> go()函数定义。

4。指导

我知道我可能必须告诉pydantic来验证这一特定内容,但我只是不知道如何确切。

  • 在这里 似乎有很多技巧我猜的任务。
  • 另一个想法是为数据属性创建一个通用类型(例如params_list:generic),然后使用验证器装饰器将其转换为列表,符合行:
class ParamsList(pydantic.BaseModel):
  params_list: ???????? #i don't know that to do here
  @p.validator("params_list")
  @classmethod
    def validate_path(cls, v) -> None:
        """validate if it's a list"""
        if type(list(v)) != list:
            raise TypeError("It's not a list. Make it become a list")
        return list(v)

help!关于如何解决它的想法?

如何

  1. 在第2.1和2.2节中描述的文件夹中重新创建示例。
  2. 还可以创建一个带有软件包的insuert.txt文件pydantichydra-core
  3. 在创建和激活Env之后,运行python3 main。 py

1. Context

How to validate a specific class in pydantic?

I'm using pydantic to validate yaml list parameters parsed by hydra, to later be passed to modeling routines. The problem is that the hydra dictionary contains not a list of values, but a class that contains those values. How can I validate those params?

2. Example

In the following example, there are 2 files:

  • cfg.yaml containing the parameters to be validated
  • main.py containing the instructions to load and validate cfg.yaml

2.1 Config File cfg.yaml

params_list:
  - 10
  - 0
  - 20

2.2 Parser/Validator file main.py

import hydra
import pydantic
from omegaconf import DictConfig, OmegaConf
from typing import List

class Test(pydantic.BaseModel):
    params_list: List[int]

@hydra.main(config_path=".", config_name="cfg.yaml")
def go(cfg: DictConfig):
    parsed_cfg = Test(**cfg)
    print(parsed_cfg)

if __name__ == "__main__":
    go()

3. Problem

When executing python3 main.py the following error arises

value is not a valid list (type=type_error.list)

That is because hydra has a specific class for dealing with lists, called omegaconf.listconfig.ListConfig, which can be checked by adding

print(type(cfg['params_list']))

right after the go() function definition.

4. Guidance

I know that I probably have to tell pydantic to validate this specific thing, but I just don't know exactly how.

  • Here are provided some tips, but it seems to much for the task I guess.
  • Another idea is to create a generic type for the data attribute (like params_list: Generic) and then use the validator decorator to transform it to a list, something along the lines:
class ParamsList(pydantic.BaseModel):
  params_list: ???????? #i don't know that to do here
  @p.validator("params_list")
  @classmethod
    def validate_path(cls, v) -> None:
        """validate if it's a list"""
        if type(list(v)) != list:
            raise TypeError("It's not a list. Make it become a list")
        return list(v)

Help!: Any idea on how to solve it?

How to Recreate Example

  1. In a folder add files described in sections 2.1 and 2.2.
  2. Also create a requirements.txt file with the packages pydantic and hydra-core
  3. After creating and activating the env, run python3 main.py

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

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

发布评论

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

评论(1

孤凫 2025-02-01 21:38:52

pydantic不接受dictconfig格式。当您尝试使用Pydantic模型解析Hydra配置时,您必须首先将DICTCONFIG转换为本机Python dict。您可以使用omegaconf.to_object(CFG)进行此操作。

我认为您使用Python 3.10或更高。注意version_base =“ 1.2”的使用以获取最新的Hydra版本。

这应该有效:

import hydra
import pydantic
from omegaconf import DictConfig, OmegaConf

class Test(pydantic.BaseModel):
    params_list: list[int]


@hydra.main(config_path=".", config_name="cfg.yaml", version_base="1.2")
def go(cfg: DictConfig):
    print(cfg)
    d_cfg = OmegaConf.to_object(cfg)
    parsed_cfg = Test(**d_cfg)
    print(parsed_cfg)


if __name__ == "__main__":
    go()

Pydantic doesn't accept the DictConfig format. When you try to parse the hydra config with the pydantic model, you must first convert the DictConfig to a native Python Dict. You do this with OmegaConf.to_object(cfg).

I assume you use Python 3.10 or higher. Note the use of version_base="1.2" to get the latest hydra version.

This should work:

import hydra
import pydantic
from omegaconf import DictConfig, OmegaConf

class Test(pydantic.BaseModel):
    params_list: list[int]


@hydra.main(config_path=".", config_name="cfg.yaml", version_base="1.2")
def go(cfg: DictConfig):
    print(cfg)
    d_cfg = OmegaConf.to_object(cfg)
    parsed_cfg = Test(**d_cfg)
    print(parsed_cfg)


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