Programs need settings that can be changed without touching the code: paths, ports, options. Two simple text formats for that are INI and TOML.
import configparser, tomllib
ini = """
[server]
host = localhost
port = 8080
debug = yes
[user]
name = ana
"""
cfg = configparser.ConfigParser()
cfg.read_string(ini)
print(cfg.sections()) # ['server', 'user']
print(cfg["server"]["host"]) # localhost
print(cfg.getint("server", "port") + 1) # 8081
print(cfg.getboolean("server", "debug")) # True
print(cfg.get("server", "timeout", fallback="30")) # 30
cfg["server"]["port"] = "9090" # values are text
cfg["new"] = {"key": "value"}
print(cfg["server"]["port"], "new" in cfg) # 9090 True
document = """
title = "Demo"
active = true
[server]
ports = [80, 443]
[[users]]
name = "ana"
[[users]]
name = "luis"
"""
data = tomllib.loads(document)
print(data["active"], data["server"]["ports"]) # True [80, 443]
print([u["name"] for u in data["users"]]) # ['ana', 'luis']
- INI: sections in square brackets and
key = valuepairs.configparserreads and writes it. All values are text; usegetint,getfloatandgetbooleanto convert them, andfallback=for default values. Keys are stored in lowercase. - TOML: more expressive. It has strings, integers, floats, booleans, dates, lists,
[table]tables and[[table]]lists of tables. It is read withtomllib.load(f)(file opened in binary mode) ortomllib.loads(text). Syntax errors raisetomllib.TOMLDecodeError. tomllibonly reads. To write TOML you need an external package; with the standard library, JSON or INI can be written.- It is good practice to separate configuration from code and to give sensible defaults when a key is missing.
You practice it in Read an INI file, Write an INI file, Read a TOML file and From TOML to JSON.