Skip to main content
Version: 1.0

Config files example

Example application

This example demonstrates the use of config files to instantiated objects.

class DBConnection:
def connect(self):
...

class MySQLConnection(DBConnection):
def __init__(self, host: str, user: str, password: str) -> None:
self.host = host
self.user = user
self.password = password

def connect(self) -> None:
print(f"MySQL connecting to {self.host}")


class PostgreSQLConnection(DBConnection):
def __init__(self, host: str, user: str, password: str, database: str) -> None:
self.host = host
self.user = user
self.password = password
self.database = database

def connect(self) -> None:
print(f"PostgreSQL connecting to {self.host}")

To support this, we can have a parallel config structure:

conf/
β”œβ”€β”€ config.yaml
└── db
β”œβ”€β”€ mysql.yaml
└── postgresql.yaml

Config files:

db/mysql.yaml
# @package _group_
_target_: my_app.MySQLConnection
host: localhost
user: root
password: 1234

db/postgresql.yaml
# @package _group_
_target_: my_app.PostgreSQLConnection
host: localhost
user: root
password: 1234
database: tutorial
config.yaml
defaults:
- db: mysql

With this, you can instantiate the object from the configuration with a single line of code:

@hydra.main(config_path="conf", config_name="config")
def my_app(cfg):
connection = hydra.utils.instantiate(cfg.db)
connection.connect()