The config
variable in the author's answer is incorrectly annotated. Hydra always fills in a DictConf
object, which is later transformed into the custom class by the OmegaConf.to_object
method. In the answer, config
is a DictConf
object, not a MyConfigSchema
object. Here is an edited answer that also integrates the updates from the current versions of the Pydantic and Hydra libraries.
from typing import cast
import hydra
from hydra.core.config_store import ConfigStore
from omegaconf import DictConfig, OmegaConf
from pydantic import field_validator
from pydantic.dataclasses import dataclass
@dataclass
class MyConfigSchema:
some_var: float
@field_validator("some_var")
@classmethod
def validate_data_dir(cls, v: float) -> float:
if v < 0:
raise ValueError(f"'some_var' can't be less than 0, got: {v}")
return v
cs = ConfigStore.instance()
cs.store(name="config_schema", node=MyConfigSchema)
@hydra.main(version_base=None, config_path="/path/to/configs", config_name="config")
def main(dict_config: DictConfig) -> None:
config = cast(MyConfigSchema, OmegaConf.to_object(dict_config))
if __name__ == "__main__":
main()
This works in combination with the following config.yaml file.
defaults:
- config_schema
- _self_
some_var: -1 # this will raise a ValueError
hydra_zen.hydrated_dataclass
in combination withhydra_zen.validates_with_pydantic
, though I haven't tried it myself. – Northrup