Skip to main content
Version: 1.1

Config files example

ย Example

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.MySQLConnectionhost: localhostuser: rootpassword: 1234
db/postgresql.yaml
_target_: my_app.PostgreSQLConnectionhost: localhostuser: rootpassword: 1234database: 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()