zope.i18n API Reference

zope.i18n

i18n support.

zope.i18n.interpolate(text, mapping=None)

Insert the data passed from mapping into the text.

First setup a test mapping:

>>> mapping = {"name": "Zope", "version": 3}

In the text we can use substitution slots like $varname or ${varname}:

>>> interpolate(u"This is $name version ${version}.", mapping)
u'This is Zope version 3.'

Interpolation variables can be used more than once in the text:

>>> interpolate(u"This is $name version ${version}. ${name} $version!",
...             mapping)
u'This is Zope version 3. Zope 3!'

In case if the variable wasn’t found in the mapping or ‘$$’ form was used no substitution will happens:

>>> interpolate(u"This is $name $version. $unknown $$name $${version}.",
...             mapping)
u'This is Zope 3. $unknown $$name $${version}.'
>>> interpolate(u"This is ${name}")
u'This is ${name}'
zope.i18n.negotiate(context)

Negotiate language.

This only works if the languages are set globally, otherwise each message catalog needs to do the language negotiation.

zope.i18n.translate(msgid, domain=None, mapping=None, context=None, target_language=None, default=None)

Translate text.

First setup some test components:

>>> from zope import component, interface
>>> import zope.i18n.interfaces
>>> @interface.implementer(zope.i18n.interfaces.ITranslationDomain)
... class TestDomain:
...
...     def __init__(self, **catalog):
...         self.catalog = catalog
...
...     def translate(self, text, *_, **__):
...         return self.catalog[text]

Normally, the translation system will use a domain utility:

>>> component.provideUtility(TestDomain(eek=u'ook'), name='my.domain')
>>> translate(u'eek', 'my.domain')
u'ook'

Normally, if no domain is given, or if there is no domain utility for the given domain, then the text isn’t translated:

>>> translate(u'eek')
u'eek'

Moreover the text will be converted to unicode:

>>> translate('eek', 'your.domain')
u'eek'

A fallback domain factory can be provided. This is normally used for testing:

>>> def fallback(domain=u''):
...     return TestDomain(eek=u'test-from-' + domain)
>>> interface.directlyProvides(
...     fallback,
...     zope.i18n.interfaces.IFallbackTranslationDomainFactory,
...     )
>>> component.provideUtility(fallback)
>>> translate(u'eek')
u'test-from-'
>>> translate(u'eek', 'your.domain')
u'test-from-your.domain'

zope.i18n.compile

zope.i18n.compile.compile_mo_file(domain, lc_messages_path)

Creates or updates a mo file in the locales folder.

zope.i18n.config

zope.i18n.format

Basic Object Formatting

This module implements basic object formatting functionality, such as date/time, number and money formatting.

class zope.i18n.format.DateTimeFormat(pattern=None, calendar=None)

DateTime formatting and parsing interface. Here is a list of possible characters and their meaning:

Symbol Meaning Presentation Example
G era designator (Text) AD
y year (Number) 1996
M month in year (Text and Number) July and 07
d day in month (Number) 10
h hour in am/pm (1-12) (Number) 12
H hour in day (0-23) (Number) 0
m minute in hour (Number) 30
s second in minute (Number) 55
S millisecond (Number) 978
E day in week (Text and Number) Tuesday
D day in year (Number) 189
F day of week in month (Number) 2 (2nd Wed in July)
w week in year (Number) 27
W week in month (Number) 2
a am/pm marker (Text) pm
k hour in day (1-24) (Number) 24
K hour in am/pm (0-11) (Number) 0
z time zone (Text) Pacific Standard Time
escape for text    
‘’ single quote  

Meaning of the amount of characters:

Text

Four or more, use full form, <4, use short or abbreviated form if it exists. (for example, “EEEE” produces “Monday”, “EEE” produces “Mon”)

Number

The minimum number of digits. Shorter numbers are zero-padded to this amount (for example, if “m” produces “6”, “mm” produces “06”). Year is handled specially; that is, if the count of ‘y’ is 2, the Year will be truncated to 2 digits. (for example, if “yyyy” produces “1997”, “yy” produces “97”.)

Text and Number

Three or over, use text, otherwise use number. (for example, “M” produces “1”, “MM” produces “01”, “MMM” produces “Jan”, and “MMMM” produces “January”.)
format(obj, pattern=None)

See zope.i18n.interfaces.IFormat

getPattern()

See zope.i18n.interfaces.IFormat

parse(text, pattern=None, asObject=True)

See zope.i18n.interfaces.IFormat

setPattern(pattern)

See zope.i18n.interfaces.IFormat

exception zope.i18n.format.DateTimeParseError

Error is raised when parsing of datetime failed.

exception zope.i18n.format.DateTimePatternParseError

DateTime Pattern Parse Error

class zope.i18n.format.NumberFormat(pattern=None, symbols={})

Specific number formatting interface. Here are the formatting rules (I modified the rules from ICU a bit, since I think they did not agree well with the real world XML formatting strings):

posNegPattern      := ({subpattern};{subpattern} | {subpattern})
subpattern         := {padding}{prefix}{padding}{integer}{fraction}
                      {exponential}{padding}{suffix}{padding}
prefix             := ''..'�' - specialCharacters *
suffix             := ''..'�' - specialCharacters *
integer            := {digitField}'0'
fraction           := {decimalPoint}{digitField}
exponential        := E integer
digitField         := ( {digitField} {groupingSeparator} |
                        {digitField} '0'* |
                        '0'* |
                        {optionalDigitField} )
optionalDigitField := ( {digitField} {groupingSeparator} |
                        {digitField} '#'* |
                        '#'* )
groupingSeparator  := ,
decimalPoint       := .
padding            := * ''..'�'

Possible pattern symbols:

0    A digit. Always show this digit even if the value is zero.
#    A digit, suppressed if zero
.    Placeholder for decimal separator
,    Placeholder for grouping separator
E    Separates mantissa and exponent for exponential formats
;    Separates formats (that is, a positive number format verses a
     negative number format)
-    Default negative prefix. Note that the locale's minus sign
     character is used.
+    If this symbol is specified the locale's plus sign character is
     used.
%    Multiply by 100, as percentage
?    Multiply by 1000, as per mille
¤    This is the currency sign. it will be replaced by a currency
     symbol. If it is present in a pattern, the monetary decimal
     separator is used instead of the decimal separator.
¤¤   This is the international currency sign. It will be replaced
     by an international currency symbol.  If it is present in a
     pattern, the monetary decimal separator is used instead of
     the decimal separator.
X    Any other characters can be used in the prefix or suffix
'    Used to quote special characters in a prefix or suffix
format(obj, pattern=None)

See zope.i18n.interfaces.IFormat

getPattern()

See zope.i18n.interfaces.IFormat

parse(text, pattern=None)

See zope.i18n.interfaces.IFormat

setPattern(pattern)

See zope.i18n.interfaces.IFormat

exception zope.i18n.format.NumberParseError

Error that can be raised when smething unexpected happens during the number parsing process.

exception zope.i18n.format.NumberPatternParseError

Number Pattern Parse Error

zope.i18n.format.buildDateTimeInfo(dt, calendar, pattern)

Create the bits and pieces of the datetime object that can be put together.

zope.i18n.format.buildDateTimeParseInfo(calendar, pattern)

This method returns a dictionary that helps us with the parsing. It also depends on the locale of course.

zope.i18n.format.parseDateTimePattern(pattern, DATETIMECHARS='aGyMdEDFwWhHmsSkKz')

This method can handle everything: time, date and datetime strings.

zope.i18n.format.parseNumberPattern(pattern)

Parses all sorts of number pattern.

zope.i18n.format.roundHalfUp(n)

Works like round() in python2.x

Implementation of round() was changed in python3 - it rounds halfs to nearest even number, so that round(0.5) == 0. This function is here to unify behaviour between python 2.x and 3.x for the purposes of this module.

zope.i18n.gettextmessagecatalog

A simple implementation of a Message Catalog.

class zope.i18n.gettextmessagecatalog.GettextMessageCatalog(language, domain, path_to_file)

A message catalog based on GNU gettext and Python’s gettext module.

getIdentifier()

See IMessageCatalog

getMessage(id)

See IMessageCatalog

queryMessage(id, default=None)

See IMessageCatalog

reload()

See IMessageCatalog

zope.i18n.interfaces

Internationalization of content objects.