Skip to content

Instantly share code, notes, and snippets.

@omry
Created October 29, 2020 19:55
Show Gist options
  • Save omry/ccaad30a0e07da712148dcf0166d47d4 to your computer and use it in GitHub Desktop.
Save omry/ccaad30a0e07da712148dcf0166d47d4 to your computer and use it in GitHub Desktop.
# @package _group_
defaults:
- schema/db/mysql
- _self_
host: localhost
port: 3306
driver: mysql
user: omry
password: secret
# @package _group_
defaults:
- schema/db/postgresql
- _self_
host: localhost
port: 5432
driver: postgresql
user: postgre_user
password: secret
timeout: 10
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
from dataclasses import dataclass
from omegaconf import OmegaConf, DictConfig
import hydra
from hydra.core.config_store import ConfigStore
@dataclass
class MySQLConfig:
host: str
port: int
user: str
password: str
driver: str = "mysql"
@dataclass
class PostGreSQLConfig:
host: str
port: int
timeout: int
user: str
password: str
driver: str = "postgresql"
cs = ConfigStore.instance()
cs.store(group="schema/db", name="mysql", node=MySQLConfig, package="db")
cs.store(group="schema/db", name="postgresql", node=PostGreSQLConfig, package="db")
@hydra.main(config_path="conf", config_name="config")
def my_app(cfg: DictConfig) -> None:
print(OmegaConf.to_yaml(cfg))
if __name__ == "__main__":
my_app()
@omry
Copy link
Author

omry commented Oct 29, 2020

Structure:

examples/advanced/automatic_config_schema
├── conf
│   ├── config.yaml
│   └── db
│       ├── mysql.yaml
│       └── postgresql.yaml
└── my_app.py

Example outputs:

omry@Coronadev:~/dev/hydra$ python examples/advanced/automatic_config_schema/my_app.py  
db:
  host: localhost
  port: 3306
  user: omry
  password: secret
  driver: mysql

omry@Coronadev:~/dev/hydra$ python examples/advanced/automatic_config_schema/my_app.py  db.port=aaa
Error merging override db.port=aaa
Value 'aaa' could not be converted to Integer
        full_key: db.port
        reference_type=Optional[MySQLConfig]
        object_type=MySQLConfig

Set the environment variable HYDRA_FULL_ERROR=1 for a complete stack trace.
omry@Coronadev:~/dev/hydra$ python examples/advanced/automatic_config_schema/my_app.py db=postgresql db.port=aaa
Error merging override db.port=aaa
Value 'aaa' could not be converted to Integer
        full_key: db.port
        reference_type=Optional[PostGreSQLConfig]
        object_type=PostGreSQLConfig

Set the environment variable HYDRA_FULL_ERROR=1 for a complete stack trace.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment