If you can use Python 3.11+, TOML is the new hotness which is included in the standard library. It's like a simpler YAML which is much more focused on being an editable config format (many TOML libraries usually don't provide a way to write TOML).
# yourconfig.toml (the filename assumed below, tho this is also a comment.)
query = "SELECT * from cities WHERE name='Unknown';"
count = 0
level = 1 # 1 = foo, 2 = bar, 3 = baz (other example comment)
name = "Check for cities whose name should be null"
suggested_fix = """
UPDATE cities
SET name=NULL
WHERE name='Unknown';"""
The provided library is tomllib
, and you can use it like so:
import tomllib
with open("yourconfig.toml") as f:
conf = tomllib.load(f)
import pprint
pprint.pprint(conf)
# {'count': 0,
# 'level': 1,
# 'name': 'Check for cities whose name should be null',
# 'query': "SELECT * from cities WHERE name='Unknown';",
# 'suggested_fix': "UPDATE cities \nSET name=NULL \nWHERE name='Unknown';"}
Note that the suggested_fix
key includes the newlines (\n
) implied by the multiline string. You can use a trailing backslash to remove them, though if the value is SQL, they don't matter, so I wouldn't clutter it up.
Other benefits are that the count
and level
values are integers. TOML's built-in types include strings, arrays/lists, maps/dicts, ints, floats, datetimes, and booleans.
TOML has rigid types that aren't "cleverly" inferred.
In YAML, on
might be a boolean or a string, depending on if you're on version 1.1 or 1.2. In TOML it's a syntax error unless you quote it. If you wanted a boolean, use exactly one of true
or false
.
In YAML, O.1
is a string (it starts with an uppercase O), in TOML it's a syntax error.
In YAML, you basically need https://yaml-multiline.info/ to figure out how to get your multiline string to be exactly what you expect, and even then it still takes me a while. In TOML it can kinda be the same as if you wrote it in Python (escaping rules are a bit different, using single/double quotes impacts it, and trailing backslashes trims whitespace)