How to Work with Tuml Files in Python

by SkillAiNest

Tuml (Tom’s Manifest Minimal Language) has become the modern standard for configuration files in Python projects. It’s more expressive than INI files and cleaner than JSON or YAML.

Since Python 3.11, included in the standard library Tumlib Module for reading and parsing Tamil files. Tuml offers several advantages over other configuration formats. It supports complex data types such as arrays and nested tables while remaining human readable. Many Python projects, including Poetry And Seteptulesuse pyproject.toml for order.

And in this tutorial, we will learn how to parse Tuml files in Python.

🔗 Here is the code on GitHub.

Conditions

To follow along with this tutorial, you will need:

  • Python 3.11 or higher: tomllib The module is part of the standard library starting with Python 3.11

  • Basic Python knowledge: Familiarity with dictionaries, file I/O, and basic syntax

  • A text editor or IDE: An editor for creating and editing Tuml and Python files

Table of Contents

  1. Understanding the TOML format

  2. How to read toml files with tomllib

  3. How to work with tuml data types

  4. How to build Tuml Config Manager

  5. How to safely handle missing values

Understanding the TOML format

Tuml files organize data into tables (similar to INI sections) but with more powerful features. Let’s create a sample configuration to understand the syntax.

create config.toml:

# Application configuration
title = "My Application"
version = "1.0.0"

(database)
host = "localhost"
port = 5432
username = "app_user"
password = "secure_password"
databases = ("myapp_db", "myapp_cache")
pool_size = 10
ssl_enabled = true

(server)
host = "0.0.0.0"
port = 8000
debug = false
allowed_hosts = ("localhost", "127.0.0.1", "example.com")

(logging)
level = "INFO"
format = "%(asctime)s - %(levelname)s - %(message)s"
handlers = ("console", "file")

(cache)
enabled = true
ttl = 3600
max_size = 1000

(features)
enable_api = true
enable_webhooks = false
rate_limit = 100

This tuml file displays key properties: simple key-value pairs, tables (segments in brackets), arrays (square brackets with comma-separated values), and various data types including strings, integers, booleans, and arrays.

How to read with Tuml files tomllib

tomllib The module is part of the Python standard library starting with version 3.11. It provides a simple interface to load tuml files such as:

import tomllib

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


app_title = config('title')
db_host = config('database')('host')
db_port = config('database')('port')

print(f"Application: {app_title}")
print(f"Database: {db_host}:{db_port}")
print(f"Config keys: {config.keys()}")

Output:

Application: My Application
Database: localhost:5432
Config keys: dict_keys(('title', 'version', 'database', 'server', 'logging', 'cache', 'features'))

Take note tomllib Files need to be opened in binary mode ('rb') load() The function parses a tuml file and returns a regular Python dictionary.

Values ​​are automatically converted to the appropriate Python types: strings remain strings, integers become INTS, booleans become true/false, and arrays become lists. Next, let’s take a closer look at working with different data types.

How to work with tuml data types

Tuml’s type system maps neatly to Python’s built-in types. Here’s how to work with different value types:

import tomllib

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


app_title = config('title')


db_port = config('database')('port')
cache_ttl = config('cache')('ttl')


debug_mode = config('server')('debug')
cache_enabled = config('cache')('enabled')


databases = config('database')('databases')
allowed_hosts = config('server')('allowed_hosts')

print(f"Databases: {databases}")
print(f"Type of databases: {type(databases)}")
print(f"Debug mode: {debug_mode}, type: {type(debug_mode)}")

with the tomllibyou don’t need special getter methods ConfigParser. Properly typed Python objects in the returned dictionary are ready to use as seen in:

Databases: ('myapp_db', 'myapp_cache')
Type of databases: 
Debug mode: False, type: 

How to build Tuml Config Manager

For production applications, wrapping the template loading in the configuration class provides better error handling and validation. Here’s how you can do it:

import tomllib
from pathlib import Path

class TOMLConfig:
    def __init__(self, config_file='config.toml'):
        self.config_file = Path(config_file)

        if not self.config_file.exists():
            raise FileNotFoundError(f"Config file not found: {config_file}")

        with open(self.config_file, 'rb') as f:
            self.config = tomllib.load(f)

    def get(self, key, default=None):
        """Get a top-level configuration value"""
        return self.config.get(key, default)

    def get_section(self, section):
        """Get an entire configuration section"""
        if section not in self.config:
            raise ValueError(f"Section '{section}' not found")
        return self.config(section)

you can use TOMLConfig Similar class:

config = TOMLConfig('config.toml')


app_title = config.get('title')
version = config.get('version')


db_config = config.get_section('database')
server_config = config.get_section('server')

print(f"{app_title} v{version}")
print(f"Database config: {db_config}")

This configuration class provides a clean interface to your tuml file. It verifies that the file exists before attempting to parse it and provides methods to safely access configuration values.

Running the above code gives this output:

My Application v1.0.0
Database config: {'host': 'localhost', 'port': 5432, 'username': 'app_user', 'password': 'secure_password', 'databases': ('myapp_db', 'myapp_cache'), 'pool_size': 10, 'ssl_enabled': True}

How to safely handle missing values

Your code needs to handle missing sequences gracefully. Here’s how to provide defaults and validate required values:

import tomllib

def load_config_safe(config_file='config.toml'):
    try:
        with open(config_file, 'rb') as f:
            return tomllib.load(f)
    except FileNotFoundError:
        print(f"Config file {config_file} not found, using defaults")
        return {}
    except tomllib.TOMLDecodeError as e:
        print(f"Error parsing TOML: {e}")
        raise

config = load_config_safe('config.toml')


db_host = config.get('database', {}).get('host', 'localhost')
db_port = config.get('database', {}).get('port', 5432)
debug = config.get('server', {}).get('debug', False)

print(f"Database: {db_host}:{db_port}")
print(f"Debug: {debug}")

Output:

Database: localhost:5432
Debug: False

This pattern uses bindings .get() Calls with defaults. If no section or key exists, you get the default value instead of the clarifier.

The result

When working with tuml files in Python, follow these guidelines:

  • Always open in binary mode: tomllib The module requires binary mode ('rb') when opening files.

  • Use Nesting Tables for Organization: Take advantage of Tuml’s ability to tame tables for complex configurations.

  • Provide defaults for optional settings: use .get() with default values ​​to make your application more flexible.

Consider using Tuml for new projects. If you’re just starting out, Tuml is a great choice for creating a python. Happy coding!

You may also like

Leave a Comment

At Skillainest, we believe the future belongs to those who embrace AI, upgrade their skills, and stay ahead of the curve.

Get latest news

Subscribe my Newsletter for new blog posts, tips & new photos. Let's stay updated!

@2025 Skillainest.Designed and Developed by Pro