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 locale paths

multiple paths 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 sub-folder 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.

Hint

see e.g. the ae namespace portion ae.gui_help loading package/module specific translation messages.

Hint

the on_app_build() app event is used by gui_help to load the app-specific translation texts on app startup.

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

in a locale folder have to exist at least one sub-folder with a name of the language code for each supported language (e.g. ‘loc/en’ for english).

in each of these sub-folders at least one message translation file with a file name ending in the string specified by the constant MSG_FILE_SUFFIX has to exist.

translatable message texts and f-strings

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}."))

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 have 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"

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

Hint

the ae portion ae.kivy.i18n is implementing translation messages for kv files and provides additional helper functions and methods.

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 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 number in count into a dict key to access the correct plural form.

register_package_translations()

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

register_translations_path([translation_path])

add/register the passed root path as 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 Union[str, Dict[str, str]]

LanguageMessages

type of the data structure storing the loaded messages

alias of Dict[str, Union[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/stable/lib/python3.9/site-packages/ae/gui_help/loc', '/home/docs/checkouts/readthedocs.org/user_builds/ae/envs/stable/lib/python3.9/site-packages/ae/kivy_qr_displayer/loc', '/home/docs/checkouts/readthedocs.org/user_builds/ae/envs/stable/lib/python3.9/site-packages/ae/kivy_sideloading/loc']

file paths to search for translations

default_locale: List[str] = ['en', '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:

old default language (or current one if new_lang get 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 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 message file.

  • domain (str) – optional domain id, e.g. the id of an app, attached process or a user. if passed then it will be used as 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 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 module scope of the package to register/add translations resources path.

no parameters needed because we use here stack_var() helper function to determine the 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 package resources and are listed in the SKIPPED_MODULES, like e.g. ae.gui_app and ae.gui_help (passing empty string ‘’ to overwrite default skip list).

register_translations_path(translation_path='')[source]

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

Parameters:

translation_path (str) – root path of a translations 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 translation message or dict with plural forms.