🎓 A1Learner
🔍
0 of 102 lessons completed

Python Config Files

A config file keeps settings outside a program's code. A setting can change without editing the program.

Read TOML from text

tomllib turns TOML text into a dictionary. A TOML table like [app] becomes a nested dictionary.

import tomllib

text = (
    "[app]\n"
    "name = \"Shop\"\n"
    "debug = true\n"
)
config = tomllib.loads(text)
print(config["app"]["name"])
print(config["app"]["debug"])

TOML keeps value types

Numbers stay numbers in TOML. You do not need to convert them yourself.

import tomllib

text = (
    "[server]\n"
    "host = \"localhost\"\n"
    "retries = 3\n"
    "\n"
    "[server.tls]\n"
    "enabled = false\n"
)
config = tomllib.loads(text)
print(config["server"]["retries"])
print(config["server"]["tls"]["enabled"])

Read INI text

INI is an older format with the same section idea. configparser reads it, but every value starts as a string.

import configparser

parser = configparser.ConfigParser()
parser.read_string(
    "[app]\n"
    "name = Shop\n"
    "port = 8000\n"
    "debug = true\n"
)
print(parser["app"]["name"])
print(parser.getint("app", "port"))
print(parser.getboolean("app", "debug"))

Ask for a fallback

fallback gives a value when a setting is missing. Your program keeps running with a sensible default.

print(parser.get("app", "theme", fallback="light"))
print(parser.getint("app", "timeout", fallback=30))

Example

import tomllib

text = (
    "[app]\n"
    "name = \"Shop\"\n"
    "port = 9000\n"
    "debug = true\n"
)
defaults = {
    "name": "My App",
    "port": 8000,
    "theme": "light",
    "debug": False,
}
config = tomllib.loads(text)
settings = dict(defaults)
settings.update(config["app"])
for key in sorted(settings):
    print(key, "=", settings[key])

Key points

  • Config file: a file of settings that a program reads when it starts
  • Use tomllib.loads() to parse TOML text (Python 3.11 and later)
  • Use ConfigParser with read_string() or read() to parse INI text
  • TOML values keep their types, like int and bool
  • INI values are strings until you use getint() or getboolean()
  • Pick TOML for new config, JSON for data, and INI only for older tools

In this example, the TOML text holds the settings a user chose. The defaults dictionary holds a value for every setting. dict(defaults) copies the defaults into settings. update() then overwrites them with the values from the text. Port 9000 and debug True come from the TOML text. Theme stays light, because the text never sets it. sorted(settings) prints the final settings in a fixed order.

Note

tomllib only reads TOML.

It cannot write TOML.

If a program must save settings, it writes another format instead.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Python Playground

Exercise

An INI file holds port = 8000 in section [app]. What does parser["app"]["port"] give you?