ae.i18n

internationalization / localization helpers

on importing this portion, it will automatically determine the default locale (language) and encoding of your operating system and user configuration.

the functions default_language() and default_encoding() - provided by this portion - are determining or changing the default language and translation texts encoding.

additional languages will be automatically loaded by the function load_language_texts().

translation texts files

translation files can be provided by your app as well as any python package and namespace portion to store translation texts. by default, they are situated in a subfolder with the name loc underneath of your app/package root folder. to load them, call the function register_package_translations() from the module using the locale texts.

translation files get loaded and merged automatically when the module is imported. the translation texts provided by this portion will be loaded first. later imported packages would overwrite the translations with the same message id of earlier imported packages.

e.g., the ae portion ae.gui is automatically loading and merging their package/module specific translation messages on module/package import and could overwrite some of the translations provided by this portion.

you can use the function register_translations_path() to specify additional locale folders with translation texts.

in a locale folder has to exist for each supported language a subfolder named as the language code (e.g. ‘loc/en’ for English). and in each of these subfolders has to exist at least one message translation file with a file name ending in the string specified by the constant MSG_FILE_SUFFIX.

the content of these files has to be a valid python literal string that can be evaluated into a dictionary of translation texts. the message to translate is the dictionary key, and the dict value is either a string with the translated text or another dictionary of translations for a pluralized message.

the following example shows the content of a translation file with 3 translatable message ids, the first one without pluralization, the second one with a single translation and the third one with all five possible pluralized translation forms:

{
    "simple translatable message": "translated message text",
    "simple pluralizable message": {'zero': "translated text if count == 0"},
    "{count} children": {
       'zero':      "no children",        # {count} would be replaced with `'0'`
       'one':       "one child",          # help text if count == 1
       'many':      "{count} children",
       'negative':  "missing children",
       '':          "undefined children"  # fallback help text if count is None
    },
}

the count value can be specified as a keyword argument to the translation functions get_text() and get_f_string().

translation functions

simple message text strings can be enclosed in the code of your application with the get_text() function provided by this portion/module:

from ae.i18n import get_text

message = get_text("any translatable message displayed to the app user.")
print(message) # prints the translated message text

for more complex messages with placeholders, you can use the get_f_string() function:

from ae.i18n import get_f_string

my_var = 69
print(get_f_string("The value of my_var is {my_var}."))

Note

to ensure the translation text can be found in the message file, do not declare the message argument passed to get_f_string() as an f-string expression (with an ‘f’ prefix).

translatable message can also be provided in various pluralization forms. to get a pluralized message, you have to pass the count keyword argument of get_text():

print(get_text("child", count=1)) # translated into "child" (in English) or e.g. "Kind" in german
print(get_text("child", count=3)) # -> "children" (in English) or e.g. "Kinder" (in german)

for pluralized message translated by the get_f_string() function, the count value has to be passed in the count item of the loc_vars:

print(get_f_string("you have {count} children", loc_vars=dict(count=1)))
# -> "you have 1 child" or e.g. "Sie haben 1 Kind"
print(get_f_string("you have {count} children", loc_vars={'count': 3}))
# -> "you have 3 children" or "Sie haben 3 Kinder"

you can load several languages into your app run-time. to get the translation for a language that is not the current default language, you have to pass the language keyword argument with the desired language code onto the call of get_text() or get_f_string():

print(get_text("message", language='es')) # returns the Spanish translation text of "message"
print(get_text("message", language='de')) # returns the German translation text of "message"

Hint

the ae portion ae.kivy.i18n is implementing additional translation and helper functions, especially for kv files and the Kivy framework.

the helper function translation() can be used to determine if a translation exists for a message text.

Module Attributes

MsgType

type of message literals in translation text files

LanguageMessages

type of the data structure storing the loaded messages

DEF_ENCODING

encoding of the messages in your app code

DEF_LANGUAGE

language code of the messages in your app code

LOADED_TRANSLATIONS

message text translations of all loaded languages

MSG_FILE_SUFFIX

name suffix of translation text files

TRANSLATIONS_PATHS

file paths to search for translations

default_locale

language and encoding code of the current language/locale

Functions

default_encoding([new_enc])

get and optionally set the default message text encoding.

default_language([new_lang])

get and optionally set the default language code.

get_f_string(f_str[, key_suffix, language, ...])

translate the passed f-string into a message string of the passed / default language.

get_text(text[, count, key_suffix, language])

translate passed text string into the current language.

load_language_file(file_name, encoding, language)

load file content encoded with the given encoding into the specified language.

load_language_texts([language, encoding, ...])

load translation texts for the given language and optional domain.

plural_key(count)

convert the number in count into a dict key to access the correct plural form.

register_package_translations()

call from the module scope of the package to register/add the translation resources path.

register_translations_path([translation_path])

add/register the passed root path as a new resource of translation texts.

translation(text[, language])

determine translation for passed text string and language.

MsgType

type of message literals in translation text files

alias of str | Dict[str, str]

LanguageMessages

type of the data structure storing the loaded messages

alias of Dict[str, str | Dict[str, str]]

DEF_ENCODING = 'UTF-8'

encoding of the messages in your app code

DEF_LANGUAGE = 'en'

language code of the messages in your app code

LOADED_TRANSLATIONS: Dict[str, Dict[str, str | Dict[str, str]]] = {}

message text translations of all loaded languages

MSG_FILE_SUFFIX = 'Msg.txt'

name suffix of translation text files

TRANSLATIONS_PATHS: List[str] = ['/home/docs/checkouts/readthedocs.org/user_builds/ae/envs/latest/lib/python3.12/site-packages/ae/i18n/loc', '/home/docs/checkouts/readthedocs.org/user_builds/ae/envs/latest/lib/python3.12/site-packages/ae/gui/loc', '/home/docs/checkouts/readthedocs.org/user_builds/ae/envs/latest/lib/python3.12/site-packages/ae/kivy_qr_displayer/loc', '/home/docs/checkouts/readthedocs.org/user_builds/ae/envs/latest/lib/python3.12/site-packages/ae/kivy_sideloading/loc', '/home/docs/checkouts/readthedocs.org/user_builds/ae/envs/latest/lib/python3.12/site-packages/ae/lisz_app_data/loc']

file paths to search for translations

default_locale: List[str] = ['C', 'UTF-8']

language and encoding code of the current language/locale

default_encoding(new_enc='')[source]

get and optionally set the default message text encoding.

Parameters:

new_enc (str) – new default encoding to be set. kept unchanged if not passed.

Return type:

str

Returns:

old default encoding (current if new_enc get not passed).

default_language(new_lang='')[source]

get and optionally set the default language code.

Parameters:

new_lang (str) – new default language code to be set. kept unchanged if not passed.

Return type:

str

Returns:

the old default language (or the current one when new_lang gets not passed).

get_text(text, count=None, key_suffix='', language='')[source]

translate passed text string into the current language.

Parameters:
  • text (str) – text message to be translated.

  • count (Optional[int]) – pass int value if the translated text has variants for their pluralization. the count value will be converted into an amount/pluralize key by the function plural_key().

  • key_suffix (str) – suffix to the key used if the translation is a dict.

  • language (str) – language code to load (def=current language code in 1st item of default_locale).

Return type:

str

Returns:

translated text message or the value passed into text if no translation text got found for the current language.

get_f_string(f_str, key_suffix='', language='', glo_vars=None, loc_vars=None)[source]

translate the passed f-string into a message string of the passed / default language.

Parameters:
  • f_str (str) – f-string to be translated and evaluated.

  • key_suffix (str) – suffix to the key used if the translation is a dict.

  • language (str) – language code to load (def=current language code in 1st item of default_locale).

  • glo_vars (Optional[Dict[str, Any]]) – global variables used in the conversion of the f-string expression to a string. the globals() of the caller of the callee will be available too and get overwritten by the items of this argument.

  • loc_vars (Optional[Dict[str, Any]]) – local variables used in the conversion of the f-string expression to a string. the locals() of the caller of the callee will be available too and get overwritten by the items of this argument. pass a numeric value in the count item of this dict for pluralized translated texts (see also count parameter of the function get_text()).

Return type:

str

Returns:

translated text message including evaluated and formatted variables/expressions of the f-string passed-in f_str. if no translation text got found for the current language, then the original text message will be returned. any syntax errors and exceptions occurring in the conversion of the f-string are silently ignored.

load_language_file(file_name, encoding, language)[source]

load file content encoded with the given encoding into the specified language.

Parameters:
  • file_name (str) – file name, inclusive path and extension to load.

  • encoding (str) – encoding id string.

  • language (str) – language id string.

load_language_texts(language='', encoding='', domain='', reset=False)[source]

load translation texts for the given language and optional domain.

Parameters:
  • language (str) – language code of the translation texts to load. use the default language if not passed.

  • encoding (str) – encoding to use to load the message file.

  • domain (str) – optional domain id, e.g., the id of an app, attached process or a user. if specified, then it will be used as the prefix for the message file name to be loaded additionally and after the default translation texts get loaded (overwriting the default translations).

  • reset (bool) – pass True to clear all previously added language/locale messages.

Return type:

str

Returns:

language code of the loaded/default language.

plural_key(count)[source]

convert the number in count into a dict key to access the correct plural form.

Parameters:

count (Optional[int]) – number of items used in the current context or None (resulting in empty string).

Return type:

str

Returns:

dict key (prefix) within the MsgType part of the translation data structure.

register_package_translations()[source]

call from the module scope of the package to register/add the translation resources path.

no parameters are needed because we use the stack_var() helper function to determine the module file path via the __file__ module variable of the caller module in the call stack. in this call we have to overwrite the default value (SKIPPED_MODULES) of the skip_modules parameter to not skip ae portions that are providing translation message resources and are listed in the SKIPPED_MODULES, like e.g. ae.gui (passing empty string ‘’ to overwrite the default skip list).

register_translations_path(translation_path='')[source]

add/register the passed root path as a new resource of translation texts.

Parameters:

translation_path (str) – root path of a translation folder structure to register, using cwd if not specified.

Return type:

bool

Returns:

True if the translation folder structure exists and got properly added/registered, else False.

translation(text, language='')[source]

determine translation for passed text string and language.

Parameters:
  • text (str) – text message to be translated.

  • language (str) – language code to load (def=current language code in 1st item of default_locale).

Return type:

Union[str, Dict[str, str], None]

Returns:

None, if not found, else the translation message string or dict with plural forms.