Skip to main content

A lightweight localization module for Python projects

Project description

toml_i18n

PyPI version License: MIT Python 3.7+

toml_i18n is a lightweight localization module for Python projects. It provides an easy way to manage and retrieve localized strings using TOML files, with support for async applications, pluralization, and context-local locales.

Installation

pip install toml-i18n

Quick Start

from toml_i18n import TomlI18n, i18n

# Initialize once
TomlI18n.initialize(locale="fr", fallback_locale="en", directory="i18n")

# Use anywhere
print(i18n("general.greeting", name="Alice"))  # "Bonjour Alice!"

Usage

Basic Setup

Step 1: Create a Directory for Translations

In your project directory, create a subdirectory for your localization files (e.g., i18n).

Step 2: Add Translation Files Inside the directory, create TOML files for your localized strings. Files are discovered recursively, so you can organize them into subdirectories:

i18n/
├── general.en.toml
├── general.fr.toml
└── features/
    ├── auth/
    │   ├── auth.en.toml
    │   └── auth.fr.toml
    └── billing/
        ├── billing.en.toml
        └── billing.fr.toml

general.en.toml:

[general]
greeting = "Hello {name}!"

general.fr.toml:

[general]
greeting = "Bonjour {name}!"

Step 3: Initialize and Use

from toml_i18n import TomlI18n, i18n

# Initialize once at app startup
TomlI18n.initialize(locale="fr", fallback_locale="en", directory="i18n")

# Retrieve translations anywhere
print(i18n("general.greeting", name="John"))  # "Bonjour John!"

Pluralization

Handle plural forms using _zero, _one, and _other suffixes:

items.en.toml:

[items]
count_zero = "No items"
count_one = "1 item"
count_other = "{count} items"
print(i18n("items.count", count=0))   # "No items"
print(i18n("items.count", count=1))   # "1 item"
print(i18n("items.count", count=5))   # "5 items"

Number Formatting

from toml_i18n import i18n_number

print(i18n_number(1234.56, decimals=2))    # "1,234.56"
print(i18n_number(1000000))                # "1,000,000"

Async/Concurrent Applications

Each async task can have its own locale without interference. The package uses Python's contextvars to provide context-local storage, ensuring thread-safe and async-safe locale isolation:

import asyncio
from toml_i18n import TomlI18n, i18n

async def handle_request(locale: str):
    TomlI18n.initialize(locale=locale)
    return i18n("general.greeting", name="User")

# Each task gets isolated locale
async def main():
    results = await asyncio.gather(
        handle_request("en"),  # Returns English
        handle_request("fr"),  # Returns French
        handle_request("de"),  # Returns German
    )

Utility Methods

# Get current locale
current = TomlI18n.get_locale()  # "fr"

# List available locales (discovers from all subdirectories)
locales = TomlI18n.get_available_locales()  # ["de", "en", "fr"]

# Check if translation exists
if TomlI18n.has_key("optional.feature"):
    print(i18n("optional.feature"))

# Change locale dynamically
TomlI18n.get_instance().set_locale("de")

Subdirectory Organization

Translation files are loaded recursively from the configured directory. Files at any depth are merged by top-level key using dictionary update semantics — the same behavior as multiple files at the root level. Files are processed in sorted path order for deterministic results.

i18n/
├── common.en.toml          # [common] keys
├── admin/
│   └── dashboard.en.toml   # [dashboard] keys
└── public/
    └── landing.en.toml     # [landing] keys

All keys from all files are available through the same i18n() interface regardless of directory depth.

Features

  • Flexible Localization: Load translations from TOML files
  • Recursive Directory Loading: Automatically discovers translation files in subdirectories, letting you organize large translation sets into logical folders
  • Fallback Locale: Automatically fall back to a default locale if a key is missing
  • Dynamic Formatting: Use placeholders in your strings for flexible output
  • Pluralization: Built-in support for plural forms (_zero, _one, _other)
  • Async-Safe: Context-local storage (via contextvars) enables safe concurrent use in async applications
  • Lightweight: Minimal dependencies, works with Python 3.7+

Links

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

toml_i18n-1.0.11.tar.gz (7.0 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

toml_i18n-1.0.11-py3-none-any.whl (6.5 kB view details)

Uploaded Python 3

File details

Details for the file toml_i18n-1.0.11.tar.gz.

File metadata

  • Download URL: toml_i18n-1.0.11.tar.gz
  • Upload date:
  • Size: 7.0 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.13.13

File hashes

Hashes for toml_i18n-1.0.11.tar.gz
Algorithm Hash digest
SHA256 187393292abfc2e9e7fd1e2f22bb3964bdd15c98ee4843b66d99fdecb8e6df7f
MD5 fa265a2c6d2f571f0b54c223d6535211
BLAKE2b-256 432ac6b828c4885fed93b9ffcbd26ecea7f7597fb415d220551f5e873088716d

See more details on using hashes here.

File details

Details for the file toml_i18n-1.0.11-py3-none-any.whl.

File metadata

  • Download URL: toml_i18n-1.0.11-py3-none-any.whl
  • Upload date:
  • Size: 6.5 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.13.13

File hashes

Hashes for toml_i18n-1.0.11-py3-none-any.whl
Algorithm Hash digest
SHA256 ba2f60c20c43dd20d2e65ad70c6595ab393ca1e870e9a223739af511329aa195
MD5 39617524222ab1bd4cfada4de79e5e82
BLAKE2b-256 999a56ab48a7e8a15fd6b8581ce8a8cb3ae5fc4a7bd36299dbafc4da3cf1694d

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page