Sub topic 3
Keeping Configuration Out of Your Logic
What this chapter assumes
You should be comfortable with Python dataclasses, the train, validate and test workflow, and running scripts from a terminal. The chapter builds on the stage functions from the previous chapter. Each stage already takes a cfg argument, and here you will define what that object is, where its values come from, and how to give each distinct configuration an identity.
The problem with values buried in code
A notebook often contains lines like RandomForestClassifier(n_estimators=100, random_state=42) and train_test_split(X, y, test_size=0.2). The numbers work, but they sit inside the logic. Three problems follow:
- Changing an experiment means editing code. The diff of a tuning run mixes logic changes with value changes, so review gets harder.
- The same value appears in several places. The seed is used by the split and by the model. If you change one and forget the other, the run is no longer controlled.
- A run cannot say what it was. Given a saved model, you cannot tell which values produced it unless you wrote them down by hand.
The fix is to collect every tunable value into one configuration object. Stages read from that object and never contain literals of their own.
What counts as configuration
Not every constant belongs in the configuration. A useful test is to ask who changes the value, and why.
| Kind of value | Example | Where it lives |
|---|---|---|
| Experiment parameter | `n_estimators`, `test_size`, `seed` | Configuration object |
| Quality threshold | `min_accuracy` | Configuration object |
| Environment setting | Data directory, output directory | Environment variable or CLI flag, kept apart from experiment parameters |
| Secret | Tracking server token, cloud credentials | Environment variable or secret store, never in a file under version control |
| Fixed algorithm detail | The name of the metric you compute | Code |
Experiment parameters and thresholds change what the model is. Environment settings change where things run. If you mix the two, the fingerprint described later changes when you move a run to another machine, even though the model is the same.
A frozen dataclass as the single source
The configuration is a frozen dataclass. This is the same class used in the pipeline code:
import dataclasses
import hashlib
import json
from dataclasses import dataclass
@dataclass(frozen=True)
class TrainConfig:
seed: int = 42
test_size: float = 0.2
n_estimators: int = 100
min_accuracy: float = 0.8
def __post_init__(self):
if not 0.0 < self.test_size < 1.0:
raise ValueError(f"test_size must be in (0, 1), got {self.test_size}")
if self.n_estimators < 1:
raise ValueError(f"n_estimators must be at least 1, got {self.n_estimators}")
if not 0.0 <= self.min_accuracy <= 1.0:
raise ValueError(f"min_accuracy must be in [0, 1], got {self.min_accuracy}")
def config_fingerprint(cfg: TrainConfig) -> str:
payload = json.dumps(dataclasses.asdict(cfg), sort_keys=True)
return hashlib.sha256(payload.encode()).hexdigest()[:12]Three choices matter here:
frozen=True. A stage cannot change a value halfway through a run. Assigning tocfg.seedraisesFrozenInstanceError. A fixed object is what makes the fingerprint trustworthy, because the object cannot drift after you compute it.- Defaults in the class. The class documents the full set of knobs and a working baseline. A reader sees every option in one place.
- Validation in
__post_init__. A bad value fails when the object is created, not twenty minutes into training.
Compared with a plain dictionary, the dataclass gives you attribute access that editors can complete, and a typo such as cfg.n_estimater fails immediately. A dictionary lookup with .get() would silently return None.
Validate at the boundary
Configuration is input. It arrives from files and command lines, so treat it like any other untrusted input and check it where it enters the program. Checks in __post_init__ run for every construction path, including tests that build a config by hand.
Validate what you can state as a rule: ranges, allowed values, and relations between fields. For example, if you later add n_folds and test_size, you can reject combinations that leave too little data. Keep validation free of side effects. It must not read data files or call the network, so that constructing a config stays cheap and safe in tests.
Python does not enforce the type annotations on dataclass fields. TrainConfig(seed="42") is accepted, and seed becomes a string. If your values come from JSON or the command line, add explicit type checks or convert them at the point of loading. Be aware that bool is a subclass of int, so n_estimators=True passes an isinstance(..., int) check.
Layering: defaults, file, command line
A common arrangement uses three layers, where later layers win:
- Defaults in the dataclass.
- A configuration file, such as one JSON file per experiment, kept in Git.
- Command-line overrides for quick changes.
The order matters. A flag such as --seed 7 should beat the file, and the file should beat the defaults. The merge should happen in one function so the rule is stated once.
Loading and overriding
This module is complete and runnable. Save it as config.py, including the class and fingerprint function shown earlier, and add the loader below it:
import argparse
from pathlib import Path
def load_config(path=None, overrides=None) -> TrainConfig:
values = {}
if path is not None:
values.update(json.loads(Path(path).read_text()))
values.update(overrides or {})
known = {f.name for f in dataclasses.fields(TrainConfig)}
unknown = set(values) - known
if unknown:
raise ValueError(f"unknown config keys: {sorted(unknown)}")
return TrainConfig(**values)
def config_from_args(argv=None) -> TrainConfig:
parser = argparse.ArgumentParser(description="Train a model")
parser.add_argument("--config", default=None, help="path to a JSON config file")
parser.add_argument("--seed", type=int)
parser.add_argument("--test-size", type=float, dest="test_size")
parser.add_argument("--n-estimators", type=int, dest="n_estimators")
parser.add_argument("--min-accuracy", type=float, dest="min_accuracy")
args = parser.parse_args(argv)
overrides = {
key: value
for key, value in vars(args).items()
if key != "config" and value is not None
}
return load_config(args.config, overrides)
if __name__ == "__main__":
cfg = config_from_args()
print(cfg)
print("fingerprint:", config_fingerprint(cfg))A file configs/baseline.json could look like this:
{
"n_estimators": 200,
"min_accuracy": 0.9
}Running python config.py --config configs/baseline.json --seed 7 produces a config with n_estimators=200, min_accuracy=0.9, seed=7 and the default test_size.
Two details keep this loader safe:
- Unknown keys are an error. If a file says
"n_estimator": 200(missing thes), a lenient loader would ignore it and train with the default of 100. The run would look correct and be wrong. Rejecting unknown keys turns a silent mistake into an immediate one. Nonemeans "not given". The loader drops flags the user did not pass, so an absent flag never overwrites a value from the file. The cost is that you cannot useNoneas a real configuration value without a different convention.
In the main program, run_pipeline(config_from_args()) is then the whole entry point. The stages never see argparse or files, only the finished object.
Fingerprinting a configuration
config_fingerprint turns a configuration into a 12-character identifier. It serializes the fields to JSON with sorted keys, so field order cannot change the result, and then hashes the text with SHA-256. Equal configurations always give equal fingerprints, and a change to any field gives a different one with overwhelming probability.
The fingerprint gives you run identity. You can name an output directory models/3f9a1c7e02ab/, attach the fingerprint to metrics, or use it later as part of a cache key. Two runs with the same fingerprint were asked to do the same thing.
Note what the fingerprint does not cover. It identifies the configuration, not the whole run. Two runs with the same fingerprint can still differ if the data changed, the code changed, or a library was upgraded. Later chapters deal with data versions and pinned environments. Treat the fingerprint as one part of a run's identity.
Choosing what goes into the hash
The example hashes every field. That is simple, but it has a consequence. min_accuracy only decides whether the model passes the gate, so it does not change the trained model. If you lower the threshold, the fingerprint changes, and any cache keyed on it would retrain a model that would be identical.
You have two options:
- Hash everything. It is simple and errs on the side of caution. You may retrain unnecessarily.
- Split the config. Put training parameters and gate settings into separate dataclasses, and fingerprint only the training part when keying a model cache. This avoids needless work but adds a class and a rule you must maintain.
For a small project, hashing everything is the better start. Split when retraining costs real time or money.
Gotchas
- Values that do not serialize.
json.dumpsfails onPath,set, and most custom objects. Keep the fields to numbers, strings, booleans, lists and plain dictionaries. If you must add aPath, convert it withstr()before hashing. Addingdefault=strtojson.dumpshides the error but can produce unstable text for objects whose string form includes a memory address. - Floating point text.
0.1 + 0.2is0.30000000000000004, not0.3. If a value is computed instead of typed, two machines or two code paths can give different text and so different fingerprints. Write configuration values as literals. - Mutable defaults. A dataclass rejects a plain
listdefault. If you need a list of feature names, usefield(default_factory=...)and store atuplewhere you can, so the object stays truly immutable. A frozen dataclass stops attribute assignment but does not stopcfg.names.append(...)on a list field. - Hidden configuration. An environment variable read deep inside a stage, such as
os.environ.get("N_JOBS"), is configuration that the fingerprint cannot see. Read environment values once, near the entry point, and put the ones that affect results into the config object. - Passing the whole object versus single values. The stages in this tutorial take
cfg, which is convenient. A stage such asevaluate(model, X_test, y_test)takes no config because it needs none, which keeps it easy to test. If a stage uses only one field, passing just that value makes its dependency explicit. Choose per stage, and prefer the narrower interface when a stage is reused elsewhere. - Config files that drift. If a file holds only overrides, you must know the code's defaults to know the final values. Print the fully resolved config at the start of every run, and record it, so the log shows the real values and not the layers.
Testing the configuration code
The configuration layer is cheap to test, and it guards against the silent failures above. These tests use pytest and its tmp_path fixture:
import json
import pytest
from config import TrainConfig, config_fingerprint, load_config
def test_same_config_gives_same_fingerprint():
assert config_fingerprint(TrainConfig()) == config_fingerprint(TrainConfig())
def test_changed_value_changes_fingerprint():
base = TrainConfig()
changed = TrainConfig(n_estimators=200)
assert config_fingerprint(base) != config_fingerprint(changed)
def test_unknown_key_is_rejected(tmp_path):
path = tmp_path / "bad.json"
path.write_text(json.dumps({"n_estimator": 200}))
with pytest.raises(ValueError, match="unknown"):
load_config(path)
def test_invalid_value_is_rejected():
with pytest.raises(ValueError, match="test_size"):
TrainConfig(test_size=1.5)
def test_override_beats_file(tmp_path):
path = tmp_path / "exp.json"
path.write_text(json.dumps({"seed": 1, "n_estimators": 50}))
cfg = load_config(path, {"seed": 7})
assert cfg.seed == 7
assert cfg.n_estimators == 50The last test pins down the layering rule. If someone reorders the merge later, it fails.
Summary of the working model
- All experiment parameters and thresholds live in one frozen, validated dataclass.
- Values arrive in layers (defaults, file, flags) and are merged in one place.
- Unknown keys and out-of-range values fail at load time.
- The resolved config is fingerprinted to give each distinct configuration a stable identifier.
- Stages receive the finished object and never parse files or flags.
Exercise
A teammate's config file contains {"n_estimator": 300}, with a missing "s". The loader they wrote ignores keys it does not recognize. What happens during training, and what change to the loader prevents it?
Show answer
Training runs without any error, but it uses the default nestimators of 100, because the misspelled key is never applied. The results look normal while the experiment is not what the teammate intended. The loader should compare the keys against the dataclass field names and raise an error listing the unknown ones, as loadconfig does.
Exercise
You add a field n_jobs: int = 1 to TrainConfig that sets how many CPU cores the forest uses. Changing it does not change the trained model for a fixed seed. Should it be part of the fingerprint used to cache trained models? Name one benefit and one cost of each choice.
Show answer
If njobs stays in the fingerprint, the benefit is simplicity and a safe default, and the cost is that moving a run to a machine with more cores changes the fingerprint and triggers a needless retrain. If you exclude it, for example by keeping it in a separate environment-settings object, the benefit is that equivalent runs share a cache entry, and the cost is an extra class and a rule to maintain. You must also be sure that njobs really does not affect results for your model, since some algorithms can give different results with different parallelism.
Exercise
Write the check that belongs in TrainConfig._postinit__ to reject a seed that is not an integer, including the bool case. Why is a plain isinstance(self.seed, int) check not enough?
Show answer
Use: if not isinstance(self.seed, int) or isinstance(self.seed, bool): raise ValueError(f"seed must be an int, got {self.seed!r}"). A plain isinstance(self.seed, int) check is not enough because bool is a subclass of int, so True would pass and be treated as the seed 1.