24. TOML Configuration

Python 3.11 added tomllib to the standard library. TOML is a readable configuration format, and it is a good fit for settings files.

24.1. Reading TOML

Use tomllib.load() to read TOML data from a file opened in binary mode.

1import tomllib
2
3with open('config.toml', 'rb') as f:
4    config = tomllib.load(f)
5
6print(config['app']['name'])
7print(config['app']['debug'])

24.2. Nested settings

TOML maps naturally to nested dictionaries.

1import tomllib
2
3with open('config.toml', 'rb') as f:
4    config = tomllib.load(f)
5
6print(config['database']['host'])
7print(config['database']['port'])

24.3. Exercise

Create a settings.toml file for a small web app with an app name, port number, and debug flag. Load it with tomllib and print each setting.

24.3.1. Solution

1import tomllib
2
3with open('settings.toml', 'rb') as f:
4    settings = tomllib.load(f)
5
6print(settings['app']['name'])
7print(settings['app']['port'])
8print(settings['app']['debug'])