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.10.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.10-py3-none-any.whl (6.5 kB view details)

Uploaded Python 3

File details

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

File metadata

  • Download URL: toml_i18n-1.0.10.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.10.tar.gz
Algorithm Hash digest
SHA256 7036da2bf50f531f878ca42ca0200949eeccd70a8fb0e7ca035469e68eba0d40
MD5 d8bf2d9d3babf6ae333fd6ccde7620de
BLAKE2b-256 7caea17da6f9bd3ec54f7495f0ffc6b61509e5b2575e4649143c9a7fd09f4c0c

See more details on using hashes here.

File details

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

File metadata

  • Download URL: toml_i18n-1.0.10-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.10-py3-none-any.whl
Algorithm Hash digest
SHA256 8fdb200570602041e6ab82470d5385bd65e9c1ef1df1c3b7ea099577a40426df
MD5 4a3188c7e2f50492ca3a5bdbd784aeb4
BLAKE2b-256 c80c46f3f613705edaf59b825136350f68471fcad374971adb8730daec0c5d67

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