Sub topic 3
Keeping Configuration Out of Your Logic
This chapter assumes you know Python functions, modules, and dataclasses; the basic train, validation, and test workflow; command-line and Git basics; and a library such as scikit-learn. The goal is to make training behavior change through configuration rather than edits scattered throughout the pipeline.
Why configuration belongs outside logic
A training script often starts with values embedded in its functions:
model = RandomForestClassifier(
n_estimators=100,
max_depth=8,
random_state=42,
)This is convenient for an experiment. It becomes difficult to manage when you compare runs. You must search the source code to discover which values were used. A small edit can also change several experiments without leaving a clear record.
Configuration is the set of values that controls a run without defining the steps of the run. Examples include:
- Random seeds
- Test-set proportions
- Model hyperparameters
- Input and output paths
- Evaluation thresholds
- Feature-selection options
The pipeline logic should describe what happens. Configuration should describe how a particular run behaves.
Use one typed configuration object
A dataclass gives the configuration a fixed structure, useful defaults, and type annotations. Making it frozen prevents a stage from changing settings while the pipeline is running.
from dataclasses import dataclass
@dataclass(frozen=True)
class TrainConfig:
seed: int = 42
test_size: float = 0.2
n_estimators: int = 100
max_depth: int | None = 8
min_accuracy: float = 0.8Every stage receives the configuration explicitly when it needs it:
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split
def split_data(X, y, cfg: TrainConfig):
return train_test_split(
X,
y,
test_size=cfg.test_size,
random_state=cfg.seed,
stratify=y,
)
def train_model(X_train, y_train, cfg: TrainConfig):
model = RandomForestClassifier(
n_estimators=cfg.n_estimators,
max_depth=cfg.max_depth,
random_state=cfg.seed,
)
return model.fit(X_train, y_train)The functions do not read hidden global variables. A test can pass a small configuration, and a production run can pass a different one. The interface also makes dependencies visible.
Fingerprint each configuration
A run identity should change when the configuration changes. A configuration fingerprint is a short hash derived from all configuration values.
import dataclasses
import hashlib
import json
def config_fingerprint(cfg: TrainConfig) -> str:
payload = json.dumps(
dataclasses.asdict(cfg),
sort_keys=True,
separators=(",", ":"),
)
return hashlib.sha256(payload.encode("utf-8")).hexdigest()[:12]
if __name__ == "__main__":
cfg = TrainConfig()
print(dataclasses.asdict(cfg))
print(config_fingerprint(cfg))Sorting the JSON keys ensures that equivalent dictionaries produce the same representation. The hash is not a secret and does not prove that the data is trustworthy. It is an identifier for this configuration.
Store the fingerprint with the run's metrics, model artifact, and source revision. If you change n_estimators from 100 to 200, the fingerprint changes. That difference helps you distinguish runs in an experiment tracker or artifact store.
Choose a configuration boundary
Small projects can construct a dataclass directly in a Python entry point. Larger projects commonly load values from a YAML, JSON, or environment-specific file, then validate them and create the dataclass.
Keep the boundary clear:
- Read external values.
- Convert them to the expected types.
- Validate constraints.
- Construct one
TrainConfig. - Pass that object through the pipeline.
For example, test_size should be greater than zero and less than one. n_estimators should be positive. A failed validation at startup is easier to diagnose than an obscure error during training.
| Concern | Configuration | Pipeline logic |
|---|---|---|
| Number of trees | `n_estimators=100` | Create and fit the estimator |
| Randomness | `seed=42` | Pass the seed to library calls |
| Quality requirement | `min_accuracy=0.8` | Compare the measured accuracy with the threshold |
Do not put secrets such as database passwords in a committed configuration file. Use a secret manager or environment variable, and record only a safe reference to the secret.
Avoid configuration drift
Configuration drift occurs when two places claim to control the same behavior. For example, a YAML file might specify n_estimators: 200 while a function still hard-codes 100. Decide which source wins and reject or remove duplicates.
Prefer a small, named configuration over a dictionary of arbitrary keys. A dictionary is flexible, but misspelled keys can remain unnoticed:
settings["n_estimator"] = 200A typed dataclass makes the intended field clear. It also gives reviewers one place to inspect the available controls.
When you add a field, consider its effect on run identity, tests, documentation, and backward compatibility. A default value can preserve old behavior, but it should be chosen deliberately.
Exercise
Exercise
Why should config_fingerprint sort JSON keys before hashing the configuration?
Show answer
Sorting gives equivalent configurations a stable representation, so the same values produce the same fingerprint even if their field order differs.