Skip to main content

Text internationalization with async context magic

Project description

Version Supported Python Version Downloads Build Status


Magic-i18n

Internationalization with special contextvars magic.

Key features:

  • Relies on a mechanism of implicit context passing for asynchronous functions.
  • Supports template formatting via %.
  • Texts are defined separately from their usage location and passed as variables.
  • Supports temporary (local) language overrides.
  • Can be used both standalone and within ASGI applications.
  • Utility for checking the correctness of texts for CICD.

Provides:

  • container for text/template variations,
  • language context manager,
  • lazy template for partial text formatting,
  • middleware for ASGI-compatible frameworks.
  • checking utility.

Install

pip install magic-i18n

Declaration and basic usage

from magic_i18n import Text, set_default_language, language

# setup global default language, must be called before running application
set_default_language('ru')

# Basic init without translations, fallback only
message = Text('text')
print(message)  # print `text`

# Text in different languages, with default language for non-defined languages
message = Text(en='text', ru='текст')
print(message)  # print `текст` (ru - default language)

# Text in different languages, with fallback for non-defined languages
message = Text('fail', en='text', ru='текст')
print(message)  # print `текст` (ru - default language)

Context manager for temporarily changing the current language.

with language('ru'):
    print(message % name)

with language(language) as lang:
    log.debug('Send with language %s', lang)
    print(message % name)

Get a string in the specified language

print(message | 'ru')
print(message | lang)

Template formatting

Template in different languages

message = Text(en='hello ${name}', ru='привет ${name}')

print(message % 'Alex')  
print(message % ('Alex',))  
print(message % {'name': 'Alex'})  
# all prints `привет Alex` (ru - default language)

Partial formatting and deferred evaluation.

lazy_template = Text(en='hello ${name}, open ${target}', ru='привет ${name}, открой ${target}')

print(lazy_template)
# print `привет ${name}, открой ${target}`

lazy_template % 'Alex'
print(lazy_template)
# print `привет Alex, открой ${target}`

lazy_template % 'Telegram'
print(lazy_template)
# print `привет Alex, открой Telegram`

lazy_template % {'target': 'Site'}  # set or replace
print(lazy_template)
# print `привет Alex, открой Site`

lazy_template(target='Calc')  # set or replace
print(lazy_template | 'en')
# print `hello Alex, open Calc`

ASGI middleware

The ASGI middleware retrieves the language from the Accept-Language header and sets it as the current language if it's present in the accept_languages option.

Options:

  • application - wrapped ASGI application.
  • default_language - (default: en) Used when the user's language is unknown or unavailable. This is the default only for ASGI and does not call set_default_language.
  • accept_languages - list of available languages. The default_language must be included in this list.
application = I18nMiddleware(
    application,
    default_language='en',
    accept_languages=['en', 'ru'],
)

The header parser pattern r'([a-zA-Z]{2}[-a-zA-Z0-9]*)' can be modified in header_parser class attribute.

I18nMiddleware.header_parser = re.compile(...)

Linter

Provides:

  • Check for required languages
  • Check that all versions of the text templates have the same arguments.
  • Prohibit text duplication
  • Spell check (requires pyspellchecker)
$ magic-i18n --help
...

$ magic-i18n example.lint_erorrs
Run magic-i18n linter
  load [examples.lint_errors]
5 text objects found
[check-arguments] Text(asd | AD4JT53R): The `ru` arguments differ from fallback
[check-arguments] Text(asd ${a} | ADJ6CPYN): The `ru` arguments differ from fallback
[deny-doubles] Text(asd ${a} | ADJ6CPYN): Double detected
[required-languages] Text(asd проверка % & тест? | C2E2VTY): Required language(s) `en` are not provided
[required-languages] Text(asd | AD4JT53R): Required language(s) `en` are not provided
Failed with 5 errors

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

magic_i18n-0.3.tar.gz (17.0 kB view details)

Uploaded Source

Built Distribution

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

magic_i18n-0.3-py3-none-any.whl (10.8 kB view details)

Uploaded Python 3

File details

Details for the file magic_i18n-0.3.tar.gz.

File metadata

  • Download URL: magic_i18n-0.3.tar.gz
  • Upload date:
  • Size: 17.0 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.13.0

File hashes

Hashes for magic_i18n-0.3.tar.gz
Algorithm Hash digest
SHA256 93fe58146402b8fb69957fc2b1e4320b9ba3cbf5bd67cb6c0378930a3fc83d7a
MD5 b5945eedf87701c19245bdafe3a3db68
BLAKE2b-256 cdc6e72e20d629efbc2eac56d45a2902c31c9313ce2060690580e030c63f6681

See more details on using hashes here.

File details

Details for the file magic_i18n-0.3-py3-none-any.whl.

File metadata

  • Download URL: magic_i18n-0.3-py3-none-any.whl
  • Upload date:
  • Size: 10.8 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.13.0

File hashes

Hashes for magic_i18n-0.3-py3-none-any.whl
Algorithm Hash digest
SHA256 9d22f7fab8b0c7d73af9368874a94e5bd12381a381acb2c4cda9428f39f6eb5c
MD5 d98c13d8960d759b551e449431c02977
BLAKE2b-256 50065e4a64456b638b738302eba5099cb6a4152bbe77876281933e140d13d575

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