"""Internationalization and localization support.
This module provides internationalization (I18N) and localization (L10N)
support for your Python programs by providing an interface to the GNU gettext
I18N refers to the operation by which a program is made aware of multiple
languages. L10N refers to the adaptation of your program, once
internationalized, to the local language and cultural habits.
# This module represents the integration of work, contributions, feedback, and
# suggestions from the following people:
# Martin von Loewis, who wrote the initial implementation of the underlying
# C-based libintlmodule (later renamed _gettext), along with a skeletal
# gettext.py implementation.
# Peter Funk, who wrote fintl.py, a fairly complete wrapper around intlmodule,
# which also included a pure-Python implementation to read .mo files if
# intlmodule wasn't available.
# James Henstridge, who also wrote a gettext.py module, which has some
# interesting, but currently unsupported experimental features: the notion of
# a Catalog class and instances, and the ability to add to a catalog file via
# Barry Warsaw integrated these modules, wrote the .install() API and code,
# and conformed all C and Python code to Python's coding standards.
# Francois Pinard and Marc-Andre Lemburg also contributed valuably to this
# J. David Ibanez implemented plural forms. Bruno Haible fixed some bugs.
# - Lazy loading of .mo files. Currently the entire catalog is loaded into
# memory, but that's probably bad for large translated programs. Instead,
# the lexical sort of original strings in GNU .mo files should be exploited
# to do binary searches and lazy initializations. Or you might want to use
# the undocumented double-hash algorithm for .mo files with hash tables, but
# you'll need to study the GNU gettext code to do this.
# - Support Solaris .mo file formats. Unfortunately, we've been unable to
# find this format documented anywhere.
import locale, copy, os, re, struct, sys
__all__ = ['NullTranslations', 'GNUTranslations', 'Catalog',
'find', 'translation', 'install', 'textdomain', 'bindtextdomain',
'bind_textdomain_codeset',
'dgettext', 'dngettext', 'gettext', 'lgettext', 'ldgettext',
'ldngettext', 'lngettext', 'ngettext',
_default_localedir = os.path.join(sys.prefix, 'share', 'locale')
def test(condition, true, false):
Implements the C expression:
Required to correctly interpret plural forms.
"""Gets a C expression as used in PO files for plural forms and returns a
Python lambda function that implements an equivalent expression.
# Security check, allow only the "n" identifier
from cStringIO import StringIO
from StringIO import StringIO
tokens = tokenize.generate_tokens(StringIO(plural).readline)
danger = [x for x in tokens if x[0] == token.NAME and x[1] != 'n']
except tokenize.TokenError:
'plural forms expression error, maybe unbalanced parenthesis'
raise ValueError, 'plural forms expression could be dangerous'
# Replace some C operators by their Python equivalents
plural = plural.replace('&&', ' and ')
plural = plural.replace('||', ' or ')
expr = re.compile(r'\!([^=])')
plural = expr.sub(' not \\1', plural)
# Regular expression and replacement function used to transform
# "a?b:c" to "test(a,b,c)".
expr = re.compile(r'(.*?)\?(.*?):(.*)')
return "test(%s, %s, %s)" % (x.group(1), x.group(2),
expr.sub(repl, x.group(3)))
# Code to transform the plural expression, taking care of parentheses
# Actually, we never reach this code, because unbalanced
# parentheses get caught in the security check at the
raise ValueError, 'unbalanced parenthesis in plural form'
s = expr.sub(repl, stack.pop())
plural = expr.sub(repl, stack.pop())
return eval('lambda n: int(%s)' % plural)
def _expand_lang(locale):
from locale import normalize
locale = normalize(locale)
COMPONENT_CODESET = 1 << 0
COMPONENT_TERRITORY = 1 << 1
COMPONENT_MODIFIER = 1 << 2
# split up the locale into its base components
mask |= COMPONENT_MODIFIER
mask |= COMPONENT_CODESET
mask |= COMPONENT_TERRITORY
if not (i & ~mask): # if all components for this combo exist ...
if i & COMPONENT_TERRITORY: val += territory
if i & COMPONENT_CODESET: val += codeset
if i & COMPONENT_MODIFIER: val += modifier
def __init__(self, fp=None):
self._output_charset = None
def add_fallback(self, fallback):
self._fallback.add_fallback(fallback)
self._fallback = fallback
def gettext(self, message):
return self._fallback.gettext(message)
def lgettext(self, message):
return self._fallback.lgettext(message)
def ngettext(self, msgid1, msgid2, n):
return self._fallback.ngettext(msgid1, msgid2, n)
def lngettext(self, msgid1, msgid2, n):
return self._fallback.lngettext(msgid1, msgid2, n)
def ugettext(self, message):
return self._fallback.ugettext(message)
def ungettext(self, msgid1, msgid2, n):
return self._fallback.ungettext(msgid1, msgid2, n)
def output_charset(self):
return self._output_charset
def set_output_charset(self, charset):
self._output_charset = charset
def install(self, unicode=False, names=None):
__builtin__.__dict__['_'] = unicode and self.ugettext or self.gettext
if hasattr(names, "__contains__"):
__builtin__.__dict__['gettext'] = __builtin__.__dict__['_']
__builtin__.__dict__['ngettext'] = (unicode and self.ungettext
__builtin__.__dict__['lgettext'] = self.lgettext
__builtin__.__dict__['lngettext'] = self.lngettext
class GNUTranslations(NullTranslations):
# Magic number of .mo files
"""Override this method to support alternative .mo formats."""
filename = getattr(fp, 'name', '')
# Parse the .mo file header, which consists of 5 little endian 32
self._catalog = catalog = {}
self.plural = lambda n: int(n != 1) # germanic plural by default
# Are we big endian or little endian?
magic = unpack('<I', buf[:4])[0]
if magic == self.LE_MAGIC:
version, msgcount, masteridx, transidx = unpack('<4I', buf[4:20])
elif magic == self.BE_MAGIC:
version, msgcount, masteridx, transidx = unpack('>4I', buf[4:20])
raise IOError(0, 'Bad magic number', filename)
# Now put all messages from the .mo file buffer into the catalog
for i in xrange(0, msgcount):
mlen, moff = unpack(ii, buf[masteridx:masteridx+8])
tlen, toff = unpack(ii, buf[transidx:transidx+8])
if mend < buflen and tend < buflen:
raise IOError(0, 'File is corrupt', filename)
# See if we're looking at GNU .mo conventions for metadata
for item in tmsg.splitlines():
k, v = item.split(':', 1)
self._info[lastk] += '\n' + item
self._charset = v.split('charset=')[1]
elif k == 'plural-forms':
plural = v[1].split('plural=')[1]
self.plural = c2py(plural)
# Note: we unconditionally convert both msgids and msgstrs to
# Unicode using the character encoding specified in the charset
# parameter of the Content-Type header. The gettext documentation
# strongly encourages msgids to be us-ascii, but some applications
# require alternative encodings (e.g. Zope's ZCML and ZPT). For
# traditional gettext applications, the msgid conversion will
# cause no problems since us-ascii should always be a subset of
# the charset encoding. We may want to fall back to 8-bit msgids
# if the Unicode conversion fails.
msgid1, msgid2 = msg.split('\x00')
tmsg = tmsg.split('\x00')
msgid1 = unicode(msgid1, self._charset)
tmsg = [unicode(x, self._charset) for x in tmsg]
for i in range(len(tmsg)):
catalog[(msgid1, i)] = tmsg[i]
msg = unicode(msg, self._charset)
tmsg = unicode(tmsg, self._charset)
# advance to next entry in the seek tables
def gettext(self, message):
tmsg = self._catalog.get(message, missing)
return self._fallback.gettext(message)
# Encode the Unicode tmsg back to an 8-bit string, if possible
return tmsg.encode(self._output_charset)
return tmsg.encode(self._charset)
def lgettext(self, message):
tmsg = self._catalog.get(message, missing)
return self._fallback.lgettext(message)
return tmsg.encode(self._output_charset)
return tmsg.encode(locale.getpreferredencoding())
def ngettext(self, msgid1, msgid2, n):
tmsg = self._catalog[(msgid1, self.plural(n))]
return tmsg.encode(self._output_charset)
return tmsg.encode(self._charset)
return self._fallback.ngettext(msgid1, msgid2, n)
def lngettext(self, msgid1, msgid2, n):
tmsg = self._catalog[(msgid1, self.plural(n))]
return tmsg.encode(self._output_charset)
return tmsg.encode(locale.getpreferredencoding())
return self._fallback.lngettext(msgid1, msgid2, n)
def ugettext(self, message):
tmsg = self._catalog.get(message, missing)
return self._fallback.ugettext(message)
def ungettext(self, msgid1, msgid2, n):
tmsg = self._catalog[(msgid1, self.plural(n))]
return self._fallback.ungettext(msgid1, msgid2, n)
# Locate a .mo file using the gettext strategy
def find(domain, localedir=None, languages=None, all=0):
# Get some reasonable defaults for arguments that were not supplied
localedir = _default_localedir
for envar in ('LANGUAGE', 'LC_ALL', 'LC_MESSAGES', 'LANG'):
val = os.environ.get(envar)
languages = val.split(':')
# now normalize and expand the languages
for nelang in _expand_lang(lang):
if nelang not in nelangs:
mofile = os.path.join(localedir, lang, 'LC_MESSAGES', '%s.mo' % domain)
if os.path.exists(mofile):
# a mapping between absolute .mo file path and Translation object
def translation(domain, localedir=None, languages=None,
class_=None, fallback=False, codeset=None):
mofiles = find(domain, localedir, languages, all=1)
return NullTranslations()
raise IOError(ENOENT, 'No translation file found for domain', domain)
# Avoid opening, reading, and parsing the .mo file after it's been done
key = (class_, os.path.abspath(mofile))
t = _translations.get(key)
with open(mofile, 'rb') as fp:
t = _translations.setdefault(key, class_(fp))
# Copy the translation object to allow setting fallbacks and
# output charset. All other instance data is shared with the
t.set_output_charset(codeset)
def install(domain, localedir=None, unicode=False, codeset=None, names=None):
t = translation(domain, localedir, fallback=True, codeset=codeset)
t.install(unicode, names)