Python i18n
python-i18n is an easy-to-use internationalization (i18n) library for Python 3, providing functionality largely inspired by Rails i18n. It allows developers to manage translations, pluralization, and placeholders using YAML or JSON files. The current version is 0.3.9, last released in August 2020, indicating a low-activity maintenance status.
Warnings
- gotcha The library primarily targets Python 3. While version 0.3.0 explicitly supported Python 2.7, subsequent developments and the current README focus on Python 3. Users attempting to use the latest version (0.3.9) with Python 2.7 may encounter compatibility issues.
- gotcha Enabling `memoization` (i18n.set('enable_memoization', True)) loads translation files into memory only once. Subsequent changes to these files on disk will not be reflected without restarting the Python interpreter. This can lead to confusion during development when updating translations.
- gotcha By default, translation keys are namespaced by their filename. For example, if you have a file `messages.en.yml` with a key `hi: 'Hello!'`, you must access it as `i18n.t('messages.hi')`. To remove this namespace, you need to configure `filename_format` (e.g., `i18n.set('filename_format', '{locale}.{format}')`).
- gotcha If `PyYAML` is installed in your environment, `python-i18n` will default to using YAML for translation files. If you intend to use JSON files even when `PyYAML` is present, you must explicitly set the file format (e.e., `i18n.set('file_format', 'json')`).
Install
-
pip install python-i18n -
pip install python-i18n[YAML]
Imports
- i18n
import i18n
Quickstart
import i18n
import os
# Configure translation path (assuming 'locales' directory exists with translation files)
# Example: locales/en.yml or locales/foo.en.yml
# Create a dummy translation file for the example
if not os.path.exists('locales'):
os.makedirs('locales')
with open('locales/en.yml', 'w') as f:
f.write('en:\n hello: "Hello world!"\n welcome: "Welcome, %{name}!"\n mail_number:\n zero: "You have no mails."\n one: "You have one mail."
many: "You have %{count} mails."
')
i18n.load_path.append('./locales')
# Set the default locale
i18n.set('locale', 'en')
# Basic translation from a file (if en.yml exists with 'en: hello: "Hello world!"')
print(i18n.t('hello'))
# Translation with placeholders
print(i18n.t('welcome', name='Bob'))
# Pluralization (requires `count` argument and specific keys in translation file)
print(i18n.t('mail_number', count=0)) # Should output 'You have no mails.'
print(i18n.t('mail_number', count=1)) # Should output 'You have one mail.'
print(i18n.t('mail_number', count=5)) # Should output 'You have 5 mails.'