Welcome to Tomli: Python’s Lightweight TOML Parser
TOML (Tom’s Obvious, Minimal Language) has become a popular choice for configuration files in modern projects due to its simplicity and readability. Tomli is an excellent Python library designed exclusively for parsing TOML files. It’s ultra-lightweight and fully compliant with the TOML specification.
In this article, we will explore the fundamentals of Tomli, dive into its APIs, provide rich code snippets, and even show you an app example that uses Tomli for configuration management.
Core Features of Tomli
- High performance TOML parser fully compatible with Python.
- Support for the latest TOML specifications.
- Designed for use in modern production environments where efficiency is critical.
Installing Tomli
pip install tomli
How to Load TOML Files
The most common use case for Tomli is loading TOML files. Here’s a quick example:
import tomli # Load a TOML string toml_string = ''' [database] user = "admin" password = "1234" host = "127.0.0.1" port = 5432 ''' parsed_data = tomli.loads(toml_string) print(parsed_data) # Output: {'database': {'user': 'admin', 'password': '1234', 'host': '127.0.0.1', 'port': 5432}}
Loading TOML from Files
Use the load
function to parse a TOML file:
import tomli with open("config.toml", "rb") as file: config = tomli.load(file) print(config)
Error Handling with Tomli
All parsing errors are represented as tomli.TOMLDecodeError
. Here’s an example:
import tomli try: broken_toml = "user = 'admin' password = '1234'" # Invalid! tomli.loads(broken_toml) except tomli.TOMLDecodeError as e: print(f"Error parsing TOML: {e}")
Working with Nested Data
Tomli gracefully handles complex, nested configurations:
toml_data = ''' [servers] [servers.alpha] ip = "10.0.0.1" dc = "us-east" [servers.beta] ip = "10.0.0.2" dc = "us-west" ''' parsed = tomli.loads(toml_data) print(parsed["servers"]["alpha"]["ip"]) # Output: 10.0.0.1
App Example Using Tomli
A Minimal Python App for Reading Configuration
Suppose we have a web application whose configurations are defined in a TOML file called app_config.toml
:
# app_config.toml [webserver] host = "0.0.0.0" port = 8080 [database] user = "app_user" password = "securepassword" name = "app_db"
Here’s how you can utilize Tomli to load and use this configuration:
import tomli # Load configuration def load_configuration(file_path): with open(file_path, "rb") as f: return tomli.load(f) # Using the configuration config = load_configuration("app_config.toml") host = config["webserver"]["host"] port = config["webserver"]["port"] db_user = config["database"]["user"] print(f"Starting server on {host}:{port}") print(f"Connecting to DB as user {db_user}")
Output:
Starting server on 0.0.0.0:8080 Connecting to DB as user app_user
Why Use Tomli?
- Compliant with the latest TOML spec for future-proofing.
- Optimized to work efficiently with a range of use cases.
- Simple and intuitive API that immediately fits into Python development workflows.
Get started with Tomli today to make your configuration loading faster, simpler, and error-free!