tomllib

The Python tomllib module allows you to parse TOML files, which are often used for configuration files due to their readability and simplicity.

This module can read TOML files and convert them into Python dictionaries, allowing you to work with configuration data in your Python applications.

Here’s a quick example:

Python
>>> import tomllib

>>> toml_data = """
... [geometry]
... size = 300
... position = "100x100"
... """

>>> tomllib.loads(toml_data)
{'geometry': {'size': 300, "position": "100x100"}}

Key Features

  • Parses TOML string and files into Python dictionaries
  • Supports all TOML data types, including tables, arrays, and nested structures
  • Handles TOML syntax natively within Python
  • Provides convenient error handling for invalid TOML data
  • Offers a standard-library solution that doesn’t requires external dependencies

Frequently Used Classes and Functions

Object Type Description
tomllib.loads() Function Parses TOML data from a string
tomllib.load() Function Loads TOML data from a file object
tomllib.TOMLDecodeError Exception Indicates that an error occurs while parsing TOML data

Examples

Parse a TOML string:

Python
>>> import tomllib

>>> toml_str = "name = \"Tom\""
>>> data = tomllib.loads(toml_str)
>>> data
{'name': 'Tom'}

Load a TOML file:

TOML config.toml
[general]
theme = "dark"
font = "Helvetica"
Python
>>> with open("config.toml", mode="rb") as toml_file:
...     config = tomllib.load(toml_file)
...

>>> config
{'general': {'theme': 'dark', 'font': 'Helvetica'}}

Common Use Cases

  • Reading configuration settings from TOML files
  • Converting TOML data into Python data structures
  • Handling configuration files in Python applications
  • Validating and handling errors in TOML configuration files
  • Loading application settings without third-party dependencies

Real-World Example

Imagine you have a configuration file for your application and need to load its contents:

TOML settings.toml
[database]
host = "localhost"
port = 5432
user = "admin"
password = "secret"

Here’s the Python code to load this file:

Python
>>> import tomllib

>>> with open("settings.toml", mode="rb") as toml_file:
...     settings = tomllib.load(toml_file)
...

>>> settings["database"]["host"]
'localhost'
>>> settings["database"]["user"]
'admin'

In this example, you use the tomllib module to read a TOML configuration file, allowing you to access and use the configuration data within your Python application.

Tutorial

Python and TOML: New Best Friends

TOML is a configuration file format that's becoming increasingly popular in the Python community. In this tutorial, you'll learn the syntax of TOML and explore how you can work with TOML files in your own projects.

intermediate data-structures

For additional information on related topics, take a look at the following resources:


By Leodanis Pozo Ramos • Updated July 25, 2025