Type Stubs for TOML
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
- breaking As a stub-only package, any update to `types-toml` can introduce stricter or changed type annotations that might cause your code to fail type checking, even if the underlying `toml` runtime library hasn't changed. This is due to evolving type definitions in `typeshed` to better reflect runtime behavior or correct previous inaccuracies.
- gotcha When using `tomli.load()` or `tomllib.load()`, files must be opened in binary read mode (`'rb'`). Opening in text mode (`'r'`) will lead to `TypeError` or incorrect parsing due to UTF-8 decoding and universal newlines being handled by the parser itself.
- gotcha `types-toml` provides stubs for the `toml` package (and by extension `tomli`/`tomllib`). It does not install the runtime `toml` parser itself. Your project must explicitly install a TOML parser (e.g., `pip install toml` or `pip install tomli`).
Install
-
pip install types-toml -
pip install tomli # For Python < 3.11 pip install toml # For the runtime library
Imports
- load
import tomli # for Python < 3.11 # or import tomllib # for Python >= 3.11
- loads
import tomli # for Python < 3.11 # or import tomllib # for Python >= 3.11
Quickstart
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.