id_translation.utils.translation_helper#

Utility for single-purpose translation tasks.

Typing rules#

Compared to Translator.translate(), typing is limited. Rules for TranslationHelper.apply():

  • When user_params = False, output= input.

  • When user_params != False, output= Any (new variable) or same (existing variable).

  • When copy = False, output= None.

Warning

When user_params = False, IDs are not converted to str. Type hints may be wrong.

See also

The ID_TRANSLATION_DISABLED environment variable.

Examples

Implementing a function with a translate arg using the helper class.

Initialization

Typically, you’d use something like a id_translation.Translator.from_config() callback with suitable arguments. Dummy translations are used here.

>>> from id_translation import Translator
>>> helper = TranslationHelper[str, str, int](
...     Translator,
...     "translate",  # for error messages
...     names="name",  # fixed translation argument
... )
>>> helper
TranslationHelper(id_translation.Translator, names='name')

The user_params_name=’translate’ argument is not printed because it’s the default.

Function definition

Arguments provided when the helper is initialized are fixed. An exception is raised if fixed arguments overlap either with user_kwargs, or with the defaults provided as keyword-arguments to apply().

In the example below, names="name" is a fixed argument (see the snippet above) and fmt="{id}:{name}" is a default argument.

>>> def example(
...     n: int,
...     *,
...     translate: UserParams[str, str, int] = True,
... ) -> list[str]:
...     items: list[str] = helper.apply(
...         list(range(n)),
...         copy=True,  # required
...         user_params=translate,  # forwarded
...         fmt="{id}:{name}",  # default - user params can override
...     )
...     return items

Note

The translatable and copy arguments are always required (for @overload typing reasons).

Let’s take our new function for a spin.

Basic usage

When user_params = translate = True, default settings are used.

>>> example(1)
['0:name-of-0']

Translation may be disabled by passing False, making the helper return immediately.

>>> example(2, translate=False)
[0, 1]

Note that the output type is list[int], rather than the expected list[str], in this case.

Aside from the obvious true | false behaviour, the helper may also act on the input type.

Argument forwarding

Dicts are interpreted as keyword-arguments for Translator.translate().

>>> example(22, translate={"fmt": "{name} (binary={id:0b})"})[-1]
'name-of-21 (binary=10101)'

Plain strings are interpreted as a temporary translation Format.

>>> example(22, translate="{name} (binary={id:0b})")[-1]
'name-of-21 (binary=10101)'

This is equivalent to passing translate={"fmt": "{name} (binary={id:0b})"}, as we did above.

Note

Users may not override the fixed_params of the helper instance.

The helper uses TranslationHelper.convert_user_params() internally, which may also be used to validate the configuration.

Documenting user arguments

Initialized helpers provide methods creating user_params and type error docstrings, which may be used as part of the docstring of functions that use translation helpers.

>>> example.__doc__.format(
...     translate=helper.make_user_params_docstring(),
...     type_error=helper.make_type_error_docstring(),
... )
>>> help(example)

See the example() function below for output.

Functions

example(n, *[, translate])

Create and translate the first n integers.

Classes

TranslationHelper(translator_or_factory[, ...])

Helper class for single-purpose translation tasks.

class TranslationHelper(translator_or_factory, user_params_name='translate', **fixed_params)[source]#

Bases: Generic[NameType, SourceType, IdType]

Helper class for single-purpose translation tasks.

Parameters:

Notes

The rsundqvist/id-translation-project template includes functions such as get_singleton(), which are suitable Translator suppliers. See the Big Corporation Inc. sample docs for more.

See also

The Typing rules and Examples sections.

apply(translatable, *, copy=True, user_params, **default_params)[source]#

Apply translation to translatable.

Keys 'copy', 'translatable' are always reserved.

Parameters:
  • translatable – A data structure to translate.

  • copy – If False, translate in-place and return None.

  • user_params – Translation options. Set to False to disable. If dict, use as keyword-arguments for Translator.translate (raises TypeError for 2 reserved keys). Other types: str = 'fmt' (see Format), float = 'max_fails' (where 1=disable check, 0=no missing IDs allowed).

  • **default_params – Default arguments for the translate method. May be overridden by user_params. If the user passes any reserved or fixed keys, a TypeError is raised.

Returns:

The original translatable if user_params is False. Otherwise, return a translated copy or None based on the copy-setting (see Translator.translate()).

Raises:

TypeError – If reserved or fixed keys are passed in the user_params.

convert_user_params(user_params, validate=True)[source]#

Convert user parameters.

Parameters:
  • user_params – End-user parameters.

  • validate – If False, skip the regular fixed parameter validation.

Returns:

Valid Translator.translate() parameters

get_translator()[source]#

Return a Translator instance.

make_docstrings(*, user_params_key=None, type_error_key='type_error')[source]#

Convenience method for creating multiple docstrings.

Parameters:
Returns:

A dict of docstrings.

make_type_error_docstring()[source]#

Create description for TypeError.

Example output below.

Raises:

TypeError – Raised if <user_params_name> is a dict containing any of the 2 the reserved keys: 'copy', 'translatable'.

Output may vary depending on helper settings.

make_user_params_docstring()[source]#

Create description for user_params.

Example output below.

Parameters:

user_params – Translation options. Set to False to disable. If dict, use as keyword-arguments for Translator.translate (raises TypeError for 2 reserved keys). Other types: str = 'fmt' (see Format), float = 'max_fails' (where 1=disable check, 0=no missing IDs allowed).

Output may vary depending on helper settings.

name_to_source()[source]#

Return the name-to-source mapping of the latest apply()-call.

example(n, *, translate=True)[source]#

Create and translate the first n integers.

Docstrings for translate and TypeError were produced by make_docstrings().

Parameters:
  • n – Number of integers to create.

  • translate – Translation options. Set to False to disable. If dict, use as keyword-arguments for Translator.translate (raises TypeError for 3 reserved keys). Other types: str = 'fmt' (see Format), float = 'max_fails' (where 1=disable check, 0=no missing IDs allowed).

Raises:

TypeError – Raised if translate is a dict containing any of the 3 the reserved keys: 'copy', 'translatable', 'names'.

Returns:

A list.