Skip to main content
Version: Next

Config files example

Β Example (Click Here)

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
_target_: my_app.MySQLConnection
host: localhost
user: root
password: 1234

db/postgresql.yaml
_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(version_base=None, config_path="conf", config_name="config")
def my_app(cfg):
connection = hydra.utils.instantiate(cfg.db)
connection.connect()