Introduction to Hydra Core
Hydra-core is a powerful framework for elegantly configuring complex applications. It allows developers to compose configurations dynamically, making it easier to manage diverse configuration scenarios for different environments and stages of development.
Main Features and APIs
Here are some of the key APIs and features of Hydra-core:
@hydra.main()
The @hydra.main()
decorator is the entry point for running a Hydra-configured application.
from hydra import main
@main(config_name="config")
def my_app(cfg):
print(cfg.pretty())
OmegaConf
Hydra leverages OmegaConf for configuration composition and manipulation.
from omegaconf import OmegaConf
config = OmegaConf.create({"db": {"host": "localhost", "port": 5432}})
print(config.db.host) # Outputs: localhost
hydra.utils.to_absolute_path()
Convenient utility to work with file systems, converting relative paths to absolute paths.
import hydra
from hydra.utils import to_absolute_path
@hydra.main(config_name="config")
def my_app(_cfg):
print(to_absolute_path("my_relative_path"))
hydra.run()
Directly launching the application defined using Hydra.
from hydra.experimental import compose, initialize
initialize(config_path="conf")
config = compose(config_name="config")
print(config)
Application Example
Let’s build a simple example application that uses several Hydra-core features:
# my_app.py
import hydra
from hydra.utils import to_absolute_path
from omegaconf import DictConfig
@hydra.main(config_name="config")
def my_app(cfg: DictConfig):
db_host = cfg.database.host
db_port = cfg.database.port
file_path = to_absolute_path(cfg.file_path)
print(f"Connecting to database at {db_host}:{db_port}")
print(f"Processing file at {file_path}")
if __name__ == "__main__":
my_app()
Assuming the configuration file config.yaml
contains:
database:
host: localhost
port: 5432
file_path: "data/example.txt"
Running the script will produce:
$ python my_app.py
Connecting to database at localhost:5432
Processing file at /absolute/path/to/data/example.txt
Hydra-core makes managing complex configurations simple and clean, enabling developers to focus on application logic.
Hash: b66371a4bd5cf200cc3b7f23556c6fcb4f9761f313136e260c5f19a53b634f69