Pyslate API reference

Config variables

class pyslate.config.DefaultConfig[source]

Default values for configuration options of Pyslate.

If you want to overwrite defaults, create a subclass of DefaultConfig and overwrite interesting values in your class’ constructor. You can also create a function which instantiates DefaultConfig, overwrites some values and then gives it to Pyslate’s constructor as keyword-argument “config”. Please note you can use keyword-arguments of Pyslate constructor to specify own parser, cache and backend. Keyword arguments set in Pyslate constructor have higher precedence than values from the config.

ALLOW_CACHE = None

Specifies if instance of Pyslate should use cache to cache any data.

When ALLOW_CACHE is True, then the cache needs to be specified as a keyword argument in Pyslate constructor. You can see the API of the SimpleMemoryCache to create your own implementation.

Default: True

ALLOW_INNER_TAGS = None

Inner tags are fields specified in the tag value using ${} syntax, e.g:

"root_tag": "I want ${item_cookie#p}!"
"item_cookie#p": "cookies"

translation: "root_tag" => "I want cookies!" When set to False, inner tags are shown as plaintext, e.g. translation: "root_tag" => "I want ${item_cookie#p}!"

Default: True

ALLOW_SWITCH_FIELDS = None

If enabled, then special switch field syntax will be enabled, e.g. %{opt1?ans1|opt2?and2} - this one will print “ans1” when the value of a “variant” argument is “opt1” and will print “ans2” when value is “opt2”. If “variant” is none of these, then first-left answer is used. If disabled, then all switch fields in tag values will be silently converted into empty strings.

Default: True

FALLBACKS = None

Dictionary of language fallbacks where key is target language and value is the fallback language e.g:

{
    "pl": "pt",
    "pt": "es",
}

In case of no “pl” fallback “pt” will be used, but fallbacks are not recursive. So if there’s no tag value for “pl” and “pt”, then it DOESN’T fall back to “es” but it just tries to use a global fallback language.

Default: {}

GLOBAL_DECORATORS = None

Dict containing decorators which are available for all languages. Decorators can be appended at the end of the inner tag or variable field to convert the value in a specific way. E.g. considering there exists a tag with key-value “cookies”: “I like cookies”

>>> pyslate.t("cookies@upper")
I LIKE COOKIES

Default: see Available decorators

GLOBAL_FALLBACK_LANGUAGE = None

If there is no tag value for a specified target language, then a fallback language is used. If there’s no tag value in both a target and fallback language, then a global fallback is used. So, for example, if global fallback is “en” and fallback for “pl” is “pt”, and we try to see tag value in “pl”, but neither “pl” nor “pt” has required tag value, then we look the tag value in language “en”. It’s a very good idea to treat global fallback as the most important language and this tag value should ALWAYS be available.

Default: “en”

LANGUAGE_SPECIFIC_DECORATORS = None

Dict containing decorators available only for a specific language. They are also available if language is current language’s fallback or a global language fallback. For information what decorators are - see doc of GLOBAL_DECORATORS variable.

Default: see Available decorators

LOCALE_FORMAT_NUMBERS = None

If true, then all the floats being interpolated into variable fields are automatically localized using language-specific Pyslate.localize

Default: True

ON_MISSING_TAG_KEY = None

Two-argument function whose return value is written to the output when the requested tag (or inner tag) and all its fallbacks are missing. The first argument is key of the missing tag, the second is dict of parameters available for interpolation into this tag’s value. It should return string displayed instead of the missing tag value. For example you can print keys of params dict to see what parameters are available.

Default: lambda name, params: “[MISSING TAG ‘{0}’]”.format(name)

ON_MISSING_VARIABLE = None

Single-argument function returning string which is added to the result when variable requested in the tag value is missing. The only argument is name of the missing variable. Should return string displayed instead of the missing variable.

Default: lambda name: “[MISSING VALUE FOR ‘{0}’]”.format(name)

PARSER_CLASS = None

Contains class used as a parser of tag value to get AST with plaintext and variable, inner tag and switch fields It’s used if you don’t specify own parser instance in Pyslate constructor’s keyword-argument. Default implementation is done using PLY parser generator.

Default: PyParser

pyslate module

class pyslate.pyslate.Pyslate(language, backend=None, config=<pyslate.config.DefaultConfig object>, context=None, cache=None, locales=None, parser=None, on_missing_tag_key_callback=None)[source]

Main class responsible for all the translation and localization. When constructed it’s necessary to set language, backend. It’s possible to set custom config, context dict and instance of cache class.

backend = None

Backend object is responsible for supplying values of tags for specified key and language from a persistent storage. It doesn’t make any further processing nor doesn’t interpret data.

cache = None

Object responsible for caching. It must implement the same methods as cache.SimpleMemoryCache. If cache is not needed, then it can be None. Even if specified, cache may not be used when config.ALLOW_CACHE is False.

config = None

Object having the same fields as config.DefaultConfig class, which specifies all configurable parameters

context = None

Contains dict whose key-value pairs are values automatically appended to kwargs argument of the translate method. They can later be used in variable or switch fields. It’s good to specify kwargs which need to be available globally, e.g. information about the person reading the text.

fallbacks = None

Dict containing language fallbacks. e.g. dict {"pl": "en"} means ‘when tag requested for “pl” is not available, then use a tag value for language “en”’

functions_deterministic = None

A dictionary where key is a name of function or a decorator and value is True/False. True means the function is deterministic for the same set of arguments and its result should be cached to be reused. It makes sense to set it to True only if a function/decorator is going to be often used with the same arguments and function processing is expensive.

functions_memory = None

A dictionary used as cache for deterministic functions and decorators. Key is a function/decorator name and value is a tuple containing a pair: list of input arguments, result. It’s discouraged to access it manually except clearing it.

global_fallback = None

Global fallback is a language which is used when tag is not available for a main language nor for language’s fallback language. It’s assumed that tag’s base (variant-less) value for global_fallback is ALWAYS available.

l(value, short=False)

Alias for localize

language = None

Language used by an instance of Pyslate as a main language.

locales = None

Dict containing information about locales available in the application. It stores information like native language name, date and time format, decimal separator and rules for plural forms available in this language. Keyword argument locales does extend, not replace the default set of locales. Locales specified in keyword argument takes higher precedence over default locales. For examples of correct locale specification see pyslate.locales.LOCALES

localize(value, short=False)[source]

Method returning localized string representation of a value specified in the argument. Currently it guarantees to correctly localize the following types: float, datetime.date, datetime.datetime, datetime.time If value cannot be localized then its string representation is returned.

Parameters:value – value to be localized
Returns:string representation of the value, localized if being instance of the supported types
on_missing_tag_key_callback = None

Contains two-parameter function which is run when some tag value cannot be got from the backend. It should return string which is written to the output instead of the missing tag. The first parameter is tag key, the second is dict of interpolable parameters (a.k.a. kwargs). You can replace it with your own implementation having some side-effect, for example logging of the missing tags.

parser = None

Object responsible for parsing the tag value string to get Abstract Syntax Tree to support variable, inner tag and switch fields. Default implementation is a pure-python PLY parser.

register_decorator(decorator_name, function, is_deterministic=False, language=None)[source]

Registers a new decorator which will be available in the translation system. Overwrites any other decorator or function with the same name.

Parameters:
  • decorator_name – name of the decorator available in the translation system
  • function – a function whose only argument is input string string and returns an altered string
  • is_deterministic – if True then return value of the decorator for specified arguments will be cached to be reused in the future. Keep it disabled unless you really know you need it.
  • language – language for which decorator will be available, If unspecified then it’s available for all languages
register_function(tag_name, function, is_deterministic=False, language=None)[source]

Registers a new custom function which will be available in the translation system. Overwrites any other decorator or function with the same name.

Parameters:
  • tag_name – name base tag key for which the function is accessible in an inner tag field. See the examples.
  • function – function with 3 arguments: - a helper (instance of PyslateHelper), which is a facade for translating specified tags or setting grammatical form of the custom function - tag_name - params (keyword arguments specified in Pyslate.translate)
  • is_deterministic – if True then return value and grammatical form of the function for specified arguments will be cached to be reused in the future. Keep it disabled unless you really know you need it.
  • language – language for which function will be available. If unspecified then it’s available for all languages
t(tag_name, **kwargs)

Alias for translate

translate(tag_name, **kwargs)[source]

Method returning fully translated tag value for a specified tag_name using kwargs as a list of keyword arguments. If there’s no tag value for specified language, then tag value for fallback language (or global fallback language) is used.

Parameters:
  • tag_name – tag key which should be translated. It can contain decorators
  • kwargs – arguments which can be interpolated into tag value
Returns:

translated value for specified tag key.

class pyslate.pyslate.PyslateHelper(pyslate)[source]

Class given as a first argument of the custom functions. It’s a facade which allows for translating or getting a grammatical form for specified tag keys. It also allows for setting a grammatical form of an entity represented by this custom function. This way a custom function can be a black-box treated exactly the same as a normal inner tag field.

form(tag_name, **kwargs)[source]

Returns grammatical form of the tag_name tag (which can be None).

get_suffix(tag_name)[source]
pass_the_suffix(tag_name)[source]
return_form(form)[source]

Specifies grammatical form of the entity represented by the custom function. It can later be retrieved by other fields of the tag value.

Parameters:form – grammatical form of this custom function
translation(tag_name, **kwargs)[source]

Returns a translated string for specified tag_name and kwargs. Delegates to Pyslate.translate method.

translation_and_form(tag_name, **kwargs)[source]

If you need both translation and grammatical form, then it’s more efficient to use it to get both at once. Returns a tuple whose first element is a translated string for specified tag_name and kwargs. The second element is grammatical form of the tag (which can be None).