Oslo Internationalization Utilities

6.7.2 · active · verified Sat Apr 11

The oslo.i18n library provides utilities for internationalization (i18n) features, primarily for translating text strings within applications or libraries. It is part of the OpenStack Oslo project and is currently at version 6.7.2. New releases often align with OpenStack development cycles, indicating an active maintenance and development cadence.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to set up `oslo.i18n` by creating an integration module (conceptually), initializing a `TranslatorFactory`, obtaining marker functions (`_`, `_LW`), marking strings for lazy translation, and finally translating them to a specific locale using `oslo_i18n.translate()`.

import os
from oslo_i18n import TranslatorFactory, enable_lazy, translate

# 1. Create an integration module (conceptually, e.g., myapp._i18n.py)
#    In a real project, this would be in a separate file and imported.
DOMAIN = 'myproject'
_translators = TranslatorFactory(domain=DOMAIN)
_ = _translators.primary  # Primary translation marker
_LW = _translators.log_warning # Log warning translation marker

# 2. Enable lazy translation (optional, but common)
enable_lazy()

# 3. Mark strings for translation
message = _('Hello, %(name)s!') % {'name': 'World'}
warning_message = _LW('Something went wrong: %s') % 'file not found'

# 4. Simulate a different locale for translation at display/log time
#    In a real app, this might come from user settings or request headers
current_locale = os.environ.get('TEST_LOCALE', 'en_US') # Example: 'es_ES'

# 5. Translate and display
#    Note: 'message' is a lazy translation object until explicitly translated or cast to string.
#    The 'translate' function is used when the target locale is known.

translated_message = translate(message, desired_locale=current_locale)
print(f"Original (lazy) message type: {type(message)}")
print(f"Translated message for '{current_locale}': {translated_message}")

# Log messages would typically be handled by a logging configuration
# with a TranslationHandler, but for demonstration, we can show direct translation.
print(f"Translated log warning for '{current_locale}': {translate(warning_message, desired_locale=current_locale)}")

view raw JSON →