DEV Community

Cover image for Using tomllib for Configuration in Python
≀Paulo Portela
≀Paulo Portela

Posted on • Updated on

Using tomllib for Configuration in Python

Introduction

This chapter introduces the tomllib library, a built-in Python module for parsing TOML (Tom's Obvious Minimal Language) files. TOML is a human-readable configuration file format gaining popularity due to its simplicity and ease of use. tomllib allows developers to easily read and access configuration data stored in TOML files, making it ideal for managing server configurations in Python applications.

Topics:

  1. Creating a TOML File with toml Library.
  2. Reading a TOML File with tomllib.
  3. Conclusion.

Creating a TOML File with toml Library

While tomllib itself doesn't offer functionalities for writing TOML files, we can leverage the toml library for this purpose (the library can be found here). Here's an example:

import toml

# Define server configuration data as a dictionary
server_config = {
    "host": "localhost",
    "port": 8080,
    "database": {
        "name": "my_database",
        "user": "admin",
        "password": "secret"
    }
}

# Write the dictionary to a TOML file
with open(file="server.toml", mode="w") as f:
    toml.dump(server_config, f)
Enter fullscreen mode Exit fullscreen mode

The above code creates a file named server.toml with the following content:

Output:

host = "localhost"
port = 8080

[database]
name = "my_database"
user = "admin"
password = "secret"
Enter fullscreen mode Exit fullscreen mode

Reading a TOML File with tomllib

Now, let's use tomllib to read the configuration data from the created TOML file:

import tomllib

# Read the TOML file
with open(file="server.toml", mode="rb") as f:
    config = tomllib.load(f)

# Access configuration values
print(f"Server host: {config['host']}")
print(f"Server port: {config['port']}")
print(f"Database name: {config['database']['name']}")
Enter fullscreen mode Exit fullscreen mode

Output:

Server host: localhost
Server port: 8080
Database name: my_database
Enter fullscreen mode Exit fullscreen mode

This code successfully reads the TOML file and accesses the configuration values using dictionary-like syntax.

Conclusion:

By combining toml for writing and tomllib for reading, we can effectively manage server configurations in Python applications using TOML files. This approach offers a clean separation between configuration data and code, improving maintainability and readability. Remember, while tomllib is included in Python 3.11 onwards, you might need to install the toml library using pip install toml.

Top comments (0)