Hydra

1.3.2 · active · verified Mon Apr 06

Hydra is an open-source Python framework developed by Facebook Research for elegantly configuring complex applications. It enables hierarchical configuration, command-line overrides, multi-run experiments, and dynamic object instantiation. Hydra maintains a regular release cadence with both major and patch versions to introduce new features and address bugs.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates a basic Hydra application. It defines a configuration in `conf/config.yaml`, uses `@hydra.main` to load it, and accesses configuration values via dot notation. It also shows how to use environment variables and retrieve working directory paths.

import hydra
from omegaconf import DictConfig, OmegaConf
import os

# Create a config directory and file (e.g., conf/config.yaml)
# In a real project, this would be a file on disk.
# For this example, we simulate it.
# Make sure to run `mkdir -p conf` first if running directly.
config_content = """
app:
  name: MyHydraApp
  version: 1.0.0
db:
  driver: mysql
  user: ${oc.env:DB_USER, omry}
  password: ${oc.env:DB_PASSWORD, secret}
"""

# Create a dummy config file for the quickstart to be runnable
# In a typical setup, 'conf/config.yaml' would exist beforehand.
if not os.path.exists('conf'):
    os.makedirs('conf')
with open('conf/config.yaml', 'w') as f:
    f.write(config_content)

@hydra.main(version_base="1.3", config_path="conf", config_name="config")
def my_app(cfg: DictConfig) -> None:
    print(f"Application Name: {cfg.app.name}")
    print(f"Database Driver: {cfg.db.driver}")
    print(f"Database User: {cfg.db.user}")
    print(f"Database Password: {cfg.db.password}")
    print(f"Original Working Directory: {hydra.utils.get_original_cwd()}")
    print(f"Current Working Directory: {os.getcwd()}")
    print(OmegaConf.to_yaml(cfg))

if __name__ == "__main__":
    # Set environment variables for demonstration if not already set
    os.environ['DB_USER'] = os.environ.get('DB_USER', 'my_db_user')
    os.environ['DB_PASSWORD'] = os.environ.get('DB_PASSWORD', 'my_db_pass')
    my_app()

    # Clean up the dummy config file for repeated runs
    os.remove('conf/config.yaml')
    os.rmdir('conf')

view raw JSON →