Type Stubs for TOML

0.10.8.20240310 · active · verified Sun Mar 29

types-toml is a PEP 561 type stub package that provides static type annotations for the 'toml' library. It enables type-checking tools such as Mypy, Pyright, Pytype, and PyCharm to analyze code that interacts with TOML files, enhancing code reliability and maintainability. This package is automatically released, often daily, by the typeshed project, ensuring up-to-date type information for the `toml` package's 0.10.* versions.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to load a TOML file using either `tomllib` (Python 3.11+) or `tomli` (earlier versions), which are type-checked by `types-toml`. It highlights the typical use case of reading configuration and how type checkers would implicitly leverage the installed stubs to validate dictionary access patterns and expected types within the loaded TOML data.

import sys
from typing import Dict, Any

if sys.version_info >= (3, 11):
    import tomllib
else:
    import tomli as tomllib

def load_config(path: str) -> Dict[str, Any]:
    with open(path, 'rb') as f:
        config = tomllib.load(f)
    return config

# Example usage with a dummy config file
# Create a dummy config.toml for demonstration
with open('config.toml', 'w') as f:
    f.write('[database]\nhost = "localhost"\nport = 5432\n')

my_config = load_config('config.toml')
print(f"Database Host: {my_config['database']['host']}")
print(f"Database Port: {my_config['database']['port']}")

# With types-toml installed, type checkers will validate access patterns
# For example, my_config['non_existent_key'] would be flagged by a type checker.

view raw JSON →