Skip to main content

On TOML as program configuration

Typically, programs have default configurations. Often, we want to override the defaults partially. Let see how easy this is with TOML in Python.

Instead of hard-coding the configurations in the source code, it is useful to store them in plain text. This is where TOML comes in. Now both the source code and configurations lend themselves to version control.

Let’s now dive into Python code. Here is a Colab notebook, if you like run the code.

Here are two configurations, base:

base_toml = """
currency = "JPY"
source_account = "CreditCard"

[Default]
payee = "Unknown"
"""

and override:

override_toml = """
[Default]
payee = "Supermarket"
"""

Loading base configuration:

base = tomllib.loads(base_toml)
print(base)
{'currency': 'JPY',
 'source_account': 'CreditCard',
 'Default': {'payee': 'Unknown'}}

Loading override configuration:

override = tomllib.loads(override_toml)
print(override)
{'Default': {'payee': 'Supermarket'}}

Execute the override with one line of code:

base.update(override)
{'currency': 'JPY',
 'source_account': 'CreditCard',
 'Default': {'payee': 'Supermarket'}}

Here, TOML is stored as strings. To read from files, use load() from tomllib (Python 3.11 and higher) or tomli. Use argparse for passing the TOML files into a program.