Data formats: XML, INI, TOML and pickle · 4 / 15 Theory

Configuration with INI and TOML

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 = value pairs. configparser reads and writes it. All values are text; use getint, getfloat and getboolean to convert them, and fallback= 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 with tomllib.load(f) (file opened in binary mode) or tomllib.loads(text). Syntax errors raise tomllib.TOMLDecodeError.
  • tomllib only 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.