💡 Python QuickBits — 📑 Parsing Configs with "tomllib" (Python v3.11+)


Description:

Python 3.11 introduced a new built-in module — tomllib — for parsing TOML configuration files.

It’s now the standard way to read TOML configs, replacing older third-party libraries like tomli or toml.


📝 Reading a TOML String

You can parse TOML data directly from a string using tomllib.loads():

import tomllib
from pprint import pprint

toml_text = """
title = "Python QuickBits"

[app]
name = "quickbits"
debug = true
version = "1.0.0"

[database]
host = "localhost"
port = 5432
enabled = true
"""

config = tomllib.loads(toml_text)

pprint(config)
print("\nApp name:", config["app"]["name"])
print("DB host:", config["database"]["host"])

tomllib.loads() reads TOML content and converts it into nested Python dictionaries and lists.


📁 Reading from a File

You can also parse TOML files directly from disk using tomllib.load().

Note that the file must be opened in binary mode ('rb').

with open("config.toml", "rb") as f:
    file_config = tomllib.load(f)

print(file_config["database"]["host"])

This is perfect for reading configuration files for CLI tools, web apps, or ML projects.


🧭 Version Notes & Safe Access

tomllib is available only in Python 3.11+.

If you’re using an older version, install tomli as a fallback:

pip install tomli

And use .get() when accessing optional keys safely:

svc = file_config.get("service", {})
print("Timeout:", svc.get("timeout", 5.0))

✅ Key Points

  • ✅ Built into Python 3.11 and later — no external libs.
  • ✅ Fast, minimal, and secure.
  • ✅ Perfect for parsing modern project configs.
  • 🐍 Use tomli for backward compatibility (read-only).

Code Snippet:

import sys             # to check Python version
import tomllib         # built-in TOML parser (Python 3.11+)
from pprint import pprint  # pretty-print nested dicts


# Example TOML string with nested tables and arrays
toml_text = """
title = "Python QuickBits"

[app]
name = "quickbits"
debug = true
version = "1.0.0"

[database]
host = "localhost"
port = 5432
enabled = true

[features]
enabled = ["lru_cache", "default_factory", "contextlib"]

[logging]
level = "INFO"
handlers = ["console", "file"]

[paths]
data_dir = "/var/data"
log_dir  = "/var/log/quickbits"
"""

# Parse the TOML string into a Python dict
config = tomllib.loads(toml_text)        # returns a nested dict-like structure

print("Parsed config (from string):")
pprint(config)                           # pretty-print for readability

# Access a few fields to demonstrate usage
print("\nApp name:", config["app"]["name"])               # 'quickbits'
print("DB host:", config["database"]["host"])             # 'localhost'
print("First feature:", config["features"]["enabled"][0]) # 'lru_cache'


# Create a sample TOML file (for demo purposes only)
sample_toml = """
[service]
name = "api"
retries = 3

[service.timeouts]
connect = 2.5
read = 5.0
"""

with open("config.toml", "w", encoding="utf-8") as f:  # write as text
    f.write(sample_toml)

# Read the TOML file with tomllib.load (requires binary mode)
with open("config.toml", "rb") as f:    # note: 'rb' is required by tomllib.load
    file_config = tomllib.load(f)

print("Parsed config (from file):")
pprint(file_config)

# Access nested values
print("\nService name:", file_config["service"]["name"])              # 'api'
print("Connect timeout:", file_config["service"]["timeouts"]["connect"])  # 2.5


# Show Python version and provide a friendly note
print(f"Python: {sys.version.split()[0]}")
if sys.version_info < (3, 11):
    print("Note: `tomllib` requires Python 3.11+. On older versions, install `tomli` (read-only).")

# Example of safe access with .get()
svc = file_config.get("service", {})
timeouts = svc.get("timeouts", {})
print("Safe read timeout:", timeouts.get("read", 10.0))   # default fallback 10.0 if missing

Link copied!

Comments

Add Your Comment

Comment Added!