Sub topic 6
Writing and loading a config file
This chapter assumes you can read basic Python and YAML, you know what a dataclass is, and you have the repository layout from the earlier chapters: importable code under src/my_project/ and settings under configs/. By the end, you will have a config file and a loader that fails loudly on bad input.
Why the loader matters as much as the file
Moving values out of code and into configs/train.yaml is only half the job. If the training script reads the file into a plain dictionary, a typo such as learing_rate produces no error. The script falls back to a default or crashes much later, deep inside the training loop. A typed loader moves that failure to the first line of the run.
A good config loader does four things:
- It reads the file without executing anything.
- It rejects keys it does not know about.
- It rejects required keys that are missing.
- It hands the rest of the code an object that cannot change during the run.
The config file
The file holds only values that change between runs: paths, the seed, and hyperparameters.
data_path: data/processed/train.csv
seed: 42
learning_rate: 0.001
batch_size: 32Keep the file flat while the project is small. Nested sections such as model: and optimizer: become useful once you have dozens of keys, but they make overrides and validation harder, so add them only when you need them.
Loading into a frozen dataclass
The dataclass is the schema. Its field names are the allowed keys, and its type hints document what each value should be.
from dataclasses import dataclass
import yaml
@dataclass(frozen=True)
class TrainConfig:
data_path: str
seed: int
learning_rate: float
batch_size: int
def apply_overrides(raw, overrides):
for item in overrides:
key, value = item.split("=", 1)
raw[key] = yaml.safe_load(value)
return raw
def load_config(path, overrides=()):
with open(path) as f:
raw = yaml.safe_load(f)
raw = apply_overrides(raw, overrides)
return TrainConfig(**raw)Three choices in this code are deliberate:
yaml.safe_load, notyaml.load.safe_loadbuilds only plain data: dictionaries, lists, strings, numbers, booleans, and null. The unrestricted loader can construct arbitrary Python objects from a file, which is unsafe for any file you did not write yourself.frozen=True. Assigning to a field after construction raisesFrozenInstanceError. A function deep in the pipeline cannot quietly change the learning rate, so the config you logged is the config that ran.- `TrainConfig(raw)`.** Python itself enforces the key check. The next section shows what that gives you.
The apply_overrides function is covered in detail in the next chapter. It is included here so the loader is complete.
What the loader catches
| Situation | Result |
|---|---|
| All four keys present, correct values | A `TrainConfig` object |
| A key is misspelled (`learing_rate`) | `TypeError`: unexpected keyword argument, plus a missing-argument error for the real key |
| A required key is absent | `TypeError`: missing required argument |
| An extra key is added | `TypeError`: unexpected keyword argument |
| `seed: "42"` (a string) | Accepted silently |
| The file is empty | `TypeError`, because `raw` is `None` |
The last two rows show the limit of a plain dataclass. Type hints are not checked at runtime, so the wrong type passes through. The empty-file error also points at the wrong problem. Both are fixed in the next section.
Adding validation
A __post_init__ method runs right after the dataclass is built. Use it to check types and ranges, and handle the empty-file case in the loader.
from dataclasses import dataclass
import yaml
@dataclass(frozen=True)
class TrainConfig:
data_path: str
seed: int
learning_rate: float
batch_size: int
def __post_init__(self):
if not isinstance(self.data_path, str):
raise TypeError(f"data_path must be a string, got {self.data_path!r}")
if not isinstance(self.seed, int) or isinstance(self.seed, bool):
raise TypeError(f"seed must be an integer, got {self.seed!r}")
if isinstance(self.learning_rate, bool) or not isinstance(
self.learning_rate, (int, float)
):
raise TypeError(
f"learning_rate must be a number, got {self.learning_rate!r}"
)
if self.learning_rate <= 0:
raise ValueError("learning_rate must be positive")
if not isinstance(self.batch_size, int) or isinstance(self.batch_size, bool):
raise TypeError(f"batch_size must be an integer, got {self.batch_size!r}")
if self.batch_size < 1:
raise ValueError("batch_size must be at least 1")
def load_config(path):
with open(path) as f:
raw = yaml.safe_load(f)
if not isinstance(raw, dict):
raise ValueError(f"{path} must contain a mapping of keys to values")
return TrainConfig(**raw)The isinstance(..., bool) checks matter because True is an instance of int in Python. Without them, batch_size: true would pass as the number 1.
Libraries such as pydantic do this work with less code and better messages. The hand-written version has no extra dependency and shows exactly what is being checked.
YAML gotchas that produce wrong types
YAML guesses types from how a value looks. Most guesses match what you expect, but a few do not.
- Scientific notation without a dot. PyYAML follows the YAML 1.1 rules, where
1e-3is a string and1.0e-3is a float. Writelearning_rate: 1.0e-3or0.001. The validation above catches the string version. - Yes and no. PyYAML reads
yes,no,on, andoffas booleans. Quote them if you mean text. - Null. An empty value or
~becomesNone. A line likedata_path:loads without error and fails the string check. - Leading zeros. A value such as
007is read as an octal integer. Quote identifiers that look like numbers.
Using the config in training code
The entry point loads the config once and passes it down. Functions receive the values they need, or the whole object, and never read the file themselves.
import argparse
import random
import numpy as np
from my_project.config import load_config
def set_seed(seed):
random.seed(seed)
np.random.seed(seed)
def main():
parser = argparse.ArgumentParser()
parser.add_argument("--config", required=True)
args = parser.parse_args()
cfg = load_config(args.config)
set_seed(cfg.seed)
print(f"Training on {cfg.data_path} with lr={cfg.learning_rate}, batch={cfg.batch_size}")
if __name__ == "__main__":
main()Run it with python -m my_project.train --config configs/train.yaml. Because the config path is an argument, you can keep several files, such as train.yaml and train_small.yaml, and choose one per run.
Relative paths like data/processed/train.csv resolve against the directory you run the command from. Run commands from the repository root, as the pipeline file in a later chapter does, so the same config works on every machine.
Testing the loader
A loader that guards against bad input deserves tests that prove it does. Use pytest's tmp_path fixture to write small config files.
import pytest
from my_project.config import load_config
def write(tmp_path, text):
path = tmp_path / "train.yaml"
path.write_text(text)
return path
GOOD = "data_path: d.csv\nseed: 1\nlearning_rate: 0.1\nbatch_size: 8\n"
def test_valid_config_loads(tmp_path):
cfg = load_config(write(tmp_path, GOOD))
assert cfg.batch_size == 8
def test_unknown_key_is_rejected(tmp_path):
with pytest.raises(TypeError):
load_config(write(tmp_path, GOOD + "learing_rate: 0.2\n"))
def test_string_learning_rate_is_rejected(tmp_path):
bad = GOOD.replace("0.1", "1e-3")
with pytest.raises(TypeError):
load_config(write(tmp_path, bad))The third test pins down the 1e-3 gotcha, so nobody reintroduces it unnoticed.
Exercise
A teammate sets learning_rate: 1e-4 in configs/train.yaml. The plain dataclass loader from the first code block runs without error, but training produces nonsense. Why does the loader accept it, and what change makes the error appear at load time?
Show answer
PyYAML follows YAML 1.1, where 1e-4 has no dot and is read as the string "1e-4". The dataclass does not check type hints at runtime, so the string is stored in learning_rate. Add a __post_init__ that checks isinstance(self.learning_rate, (int, float)) and raises TypeError, as in the validated version. Writing 1.0e-4 or 0.0001 in the file also fixes the value itself.
Exercise
Why is TrainConfig declared with frozen=True, and what happens if the training loop runs cfg.batch_size = 64?
Show answer
A frozen dataclass cannot be modified after construction, so the config logged at the start of a run is guaranteed to be the one used throughout. The assignment raises dataclasses.FrozenInstanceError. To try a different batch size, change the file or pass an override and start a new run.