Config files

Load JSON settings instead of scattering magic numbers.

Magic numbers in source (0.16 in three files) drift. Put settings in JSON (or similar) and load them once.

Goal

Write config.json, load it, and price a line with the file’s tax.

Write and load

import json
from pathlib import Path

Path("config.json").write_text(
    '{"city": "Nairobi", "tax": 0.16, "currency": "KES"}\n',
    encoding="utf-8",
)

cfg = json.loads(Path("config.json").read_text(encoding="utf-8"))
print(cfg["city"], cfg["tax"], cfg["currency"])

Use the config

import json
from pathlib import Path

Path("config.json").write_text(
    '{"city": "Kisumu", "tax": 0.16}\n',
    encoding="utf-8",
)
cfg = json.loads(Path("config.json").read_text(encoding="utf-8"))

def line_total(units, price, tax):
    return round(units * price * (1 + tax), 2)

print(cfg["city"], line_total(2, 10, cfg["tax"]))

Banner file

Download config.json, Add files, then:

import json
from pathlib import Path

cfg = json.loads(Path("config.json").read_text(encoding="utf-8"))
print(sorted(cfg.keys()))
print(cfg["city"])
Pitfall

Do not eval a config file. json.loads is enough for this course. YAML and TOML are extra libraries this tab may not have.