rics.translation.offline#

Offline (in-memory) translation classes.

Classes

Format(fmt)

Format specification for translations strings.

FormatApplier(translations)

Base class for application of Format specifications.

DefaultFormatApplier(translations)

Default format applier implementation.

TranslationMap(source_translations[, ...])

Storage class for fetched translations.

MagicDict(real_translations[, default_value])

Immutable mapping for translated IDs.

class Format(fmt: str)[source]#

Bases: object

Format specification for translations strings.

Translation formats are similar to regular f-strings, with two important exceptions:

  1. Positional placeholders ('{}') may not be used; correct form is '{placeholder-name}'.

  2. Substrings surrounded by '[]' denote an optional element. Optional elements..

    • Must contain at least one placeholder.

    • Are rendered only if all of its placeholders are defined.

    • Are rendered without delimiting brackets.

Hint

Literal angle brackets are added by doubling the wanted character, as for '{' and '}' in plain Python f-strings. For example, '[[' will render a '['-literal.

Parameters

fmt – A translation fstring.

Examples

A format string with an optionl element.

>>> from rics.translation.offline import Format
>>> fmt = Format('{id}:{name}[, nice={is_nice}]')

The Format class when used directly only returns required placeholders by default..

>>> fmt.fstring(), fmt.fstring().format(id=0, name='Tarzan')
('{id}:{name}', '0:Tarzan')

..but the placeholders attribute can be used to retrieve all placeholders, required and optional:

>>> fmt.placeholders
('id', 'name', 'is_nice')
>>> fmt.fstring(fmt.placeholders), fmt.fstring(fmt.placeholders).format(id=1, name='Morris', is_nice=True)
('{id}:{name}, nice={is_nice}', '1:Morris, nice=True')
fstring(placeholders: Optional[Iterable[str]] = None, positional: bool = False) str[source]#

Create a format string for the given placeholders.

Parameters
  • placeholders – Keys to keep. Passing None is equivalent to passing required_placeholders.

  • positional – If True, remove names to return a positional fstring.

Returns

An fstring with optional elements removed unless included in placeholders.

Raises

KeyError – If required placeholders are missing.

static parse(fmt: Union[str, Format]) Format[source]#

Parse a format.

Parameters

fmt – Input to parse.

Returns

A Format instance.

property placeholders: Tuple[str, ...]#

All placeholders in the order in which they appear.

property required_placeholders: Tuple[str, ...]#

All required placeholders in the order in which they appear.

property optional_placeholders: Tuple[str, ...]#

All optional placeholders in the order in which they appear.

class FormatApplier(translations: PlaceholderTranslations)[source]#

Bases: ABC, Generic[IdType, NameType, SourceType]

Base class for application of Format specifications.

Parameters

translations – Matrix of ID translation components returned by fetchers.

Raises

ValueError – If default is given and any placeholder names are missing.

property positional: bool#

If True, names are stripped from fstring placeholders.

property source: SourceType#

Return translation source.

property placeholders: List[str]#

Return placeholder names in sorted order.

class DefaultFormatApplier(translations: PlaceholderTranslations)[source]#

Bases: FormatApplier

Default format applier implementation.

class TranslationMap(source_translations: Dict[SourceType, PlaceholderTranslations], name_to_source: Dict[NameType, SourceType] = None, fmt: Union[str, Format] = None, default_fmt: Union[str, Format] = None, default_fmt_placeholders: InheritedKeysDict[SourceType, str, Any] = None)[source]#

Bases: Mapping, Generic[NameType, SourceType, IdType]

Storage class for fetched translations.

Parameters
  • source_translations – Fetched translations {source: PlaceholderTranslations}.

  • name_to_source – Mappings {name: source}, but may be overridden by the user.

  • fmt – A translation format. Must be given to use as a mapping.

  • default_fmt – Alternative format specification to use instead of fmt for fallback translation.

  • default_fmt_placeholders – Per-source default placeholder values.

Notes

Type checking of fmt and default_fmt_placeholders attributes may fail due to mypy#3004

FORMAT_APPLIER_TYPE#

alias of DefaultFormatApplier

apply(name: NameType, fmt: Optional[Union[str, Format]] = None, default_fmt: Optional[Union[str, Format]] = None) MagicDict[IdType][source]#

Create translations for names. Note: __getitem__ delegates to this method.

Parameters
  • name – A name to translate.

  • fmt – Format to use. If None, fall back to init format.

  • default_fmt – Alternative format for default translation. Resolution: Arg -> init arg, fmt arg, init fmt arg

Returns

Translations for name as a dict {id: translation}.

Raises
  • ValueError – If fmt=None and initialized without fmt.

  • KeyError – If trying to translate name which is not known.

property names: List[NameType]#

Return names that can be translated.

property sources: List[SourceType]#

Return translation sources.

property name_to_source: Dict[NameType, SourceType]#

Return name-to-source mapping.

property fmt: Optional[Format]#

Return the translation format.

property default_fmt: Optional[Format]#

Return the format specification to use instead of fmt for fallback translation.

property default_fmt_placeholders: InheritedKeysDict#

Return the default translations used for default_fmt_placeholders placeholders.

property reverse_mode: bool#

Return reversed mode status flag.

If set, the mappings returned by apply() (and therefore also __getitem__ are reversed.

Returns

Reversal status flag.

copy() TranslationMap[NameType, SourceType, IdType][source]#

Make a copy of this TranslationMap.

class MagicDict(real_translations: Dict[IdType, str], default_value: Optional[str] = None)[source]#

Bases: Mapping[IdType, str]

Immutable mapping for translated IDs.

If default_value is given, it is used as the default answer for any calls to __getitem__ where the key is not in translated_ids.

Parameters
  • real_translations – A dict holding real translations.

  • default_value – A string with exactly one or zero placeholders.

property default_value: Optional[str]#

Return the default string value to return for unknown keys, if any.

Modules

rics.translation.offline.parse_format_string

Utility module for parsing raw Format input strings.

rics.translation.offline.types

Types used for offline translation.