id_translation.utils.translation_helper#
Utility for single-purpose translation tasks.
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. For our purposes however, dummy translations are enough.
>>> 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 and fmt="{id}:{name}" is a default argument. The
translatable (= list(range(n))) and copy arguments are always required, but cannot be defined as fixed
arguments. The reasons for this are mostly related to the use of typing.overload().
>>> 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
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 the output is of type list[int], rather than expected list[str], in this case.
See also
The ID_TRANSLATION_DISABLED environment variable.
Aside from the obvious true|false behaviour, the TranslationHelper() may also act on the input type. The
helper can be configured what input that the user may pass; see the fixed_params argument of the class. Use
TranslationHelper.convert_user_params() to validate the configuration.
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.
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
|
Create and translate the first n integers. |
Classes
|
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.
Typing rules
Compared to
Translator.translate(), typing is limited. Rules forTranslationHelper.apply():When
user_params=False, output= input.When
user_params != False, output=Any(new variable) or same (existing variable).When
copy=False, output=None.
Note that
user_params=Falsealways takes precedence, as the translation process is aborted without anyTranslatorinvolvement.- Parameters:
translator_or_factory – A callable
() -> Translatoror an initializedTranslator.user_params_name – Used for reporting errors.
**fixed_params – Fixed parameters for
Translator.translate(). Attempting to override these inTranslationHelper.apply()will raise an error.
See also
If you are using the rsundqvist/id-translation-project template, there are several namespace-functions which may be suitable
Translatorsuppliers.Links lead to the generated documentation for the Big Corporation Inc. sample project.
- 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 returnNone.user_params – Translation options. Set to
Falseto disable (True= use defaults). Ifdict, use as keyword-arguments forTranslator.translate(raisesTypeErrorfor 2 reserved keys). Other types:str='fmt'(seeFormat),float='max_fails'(where 0=disable check, 1=no missing IDs allowed).**default_params – Default arguments for the
translatemethod. May be overridden by user_params. If the user passes any reserved or fixed keys, aTypeErroris raised.
- Returns:
The original translatable if user_params is
False. Otherwise, return a translated copy orNonebased on the copy-setting (seeTranslator.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
- make_docstrings(*, user_params_key=None, type_error_key='type_error')[source]#
Convenience method for creating multiple docstrings.
- Parameters:
user_params_key – Key for
make_user_params_docstring()output. Default is user_params_name.type_error_key – Key for
make_type_error_docstring()output.
- 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
dictcontaining 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
Falseto disable (True= use defaults). Ifdict, use as keyword-arguments forTranslator.translate(raisesTypeErrorfor 2 reserved keys). Other types:str='fmt'(seeFormat),float='max_fails'(where 0=disable check, 1=no missing IDs allowed).
Output may vary depending on helper settings.
- example(n, *, translate=True)[source]#
Create and translate the first n integers.
Docstrings for translate and
TypeErrorwere produced bymake_docstrings().- Parameters:
n – Number of integers to create.
translate – Translation options. Set to
Falseto disable (True= use defaults). Ifdict, use as keyword-arguments forTranslator.translate(raisesTypeErrorfor 3 reserved keys). Other types:str='fmt'(seeFormat),float='max_fails'(where 0=disable check, 1=no missing IDs allowed).
- Raises:
TypeError – Raised if translate is a
dictcontaining any of the 3 the reserved keys:'copy','translatable','names'.- Returns:
A list.