Back to index

python3.2  3.2.2
Classes | Functions | Variables
gettext Namespace Reference

Classes

class  NullTranslations
class  GNUTranslations

Functions

def c2py
def _expand_lang
def find
def translation
def install
def textdomain
def bindtextdomain
def bind_textdomain_codeset
def dgettext
def ldgettext
def dngettext
def ldngettext
def gettext
def lgettext
def ngettext
def lngettext

Variables

list __all__
tuple _default_localedir = os.path.join(sys.prefix, 'share', 'locale')
dictionary _translations = {}
dictionary _localedirs = {}
dictionary _localecodesets = {}
string _current_domain = 'messages'
 Catalog = translation

Detailed Description

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
message catalog library.

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.

Function Documentation

def gettext._expand_lang (   loc) [private]

Definition at line 111 of file gettext.py.

00111 
00112 def _expand_lang(loc):
00113     loc = locale.normalize(loc)
00114     COMPONENT_CODESET   = 1 << 0
00115     COMPONENT_TERRITORY = 1 << 1
00116     COMPONENT_MODIFIER  = 1 << 2
00117     # split up the locale into its base components
00118     mask = 0
00119     pos = loc.find('@')
00120     if pos >= 0:
00121         modifier = loc[pos:]
00122         loc = loc[:pos]
00123         mask |= COMPONENT_MODIFIER
00124     else:
00125         modifier = ''
00126     pos = loc.find('.')
00127     if pos >= 0:
00128         codeset = loc[pos:]
00129         loc = loc[:pos]
00130         mask |= COMPONENT_CODESET
00131     else:
00132         codeset = ''
00133     pos = loc.find('_')
00134     if pos >= 0:
00135         territory = loc[pos:]
00136         loc = loc[:pos]
00137         mask |= COMPONENT_TERRITORY
00138     else:
00139         territory = ''
00140     language = loc
00141     ret = []
00142     for i in range(mask+1):
00143         if not (i & ~mask):  # if all components for this combo exist ...
00144             val = language
00145             if i & COMPONENT_TERRITORY: val += territory
00146             if i & COMPONENT_CODESET:   val += codeset
00147             if i & COMPONENT_MODIFIER:  val += modifier
00148             ret.append(val)
00149     ret.reverse()
00150     return ret
00151 
00152 

Here is the call graph for this function:

Here is the caller graph for this function:

def gettext.bind_textdomain_codeset (   domain,
  codeset = None 
)

Definition at line 452 of file gettext.py.

00452 
00453 def bind_textdomain_codeset(domain, codeset=None):
00454     global _localecodesets
00455     if codeset is not None:
00456         _localecodesets[domain] = codeset
00457     return _localecodesets.get(domain)
00458 

def gettext.bindtextdomain (   domain,
  localedir = None 
)

Definition at line 445 of file gettext.py.

00445 
00446 def bindtextdomain(domain, localedir=None):
00447     global _localedirs
00448     if localedir is not None:
00449         _localedirs[domain] = localedir
00450     return _localedirs.get(domain, _default_localedir)
00451 

Here is the caller graph for this function:

def gettext.c2py (   plural)
Gets a C expression as used in PO files for plural forms and returns a
Python lambda function that implements an equivalent expression.

Definition at line 61 of file gettext.py.

00061 
00062 def c2py(plural):
00063     """Gets a C expression as used in PO files for plural forms and returns a
00064     Python lambda function that implements an equivalent expression.
00065     """
00066     # Security check, allow only the "n" identifier
00067     import token, tokenize
00068     tokens = tokenize.generate_tokens(io.StringIO(plural).readline)
00069     try:
00070         danger = [x for x in tokens if x[0] == token.NAME and x[1] != 'n']
00071     except tokenize.TokenError:
00072         raise ValueError('plural forms expression error, maybe unbalanced parenthesis')
00073     else:
00074         if danger:
00075             raise ValueError('plural forms expression could be dangerous')
00076 
00077     # Replace some C operators by their Python equivalents
00078     plural = plural.replace('&&', ' and ')
00079     plural = plural.replace('||', ' or ')
00080 
00081     expr = re.compile(r'\!([^=])')
00082     plural = expr.sub(' not \\1', plural)
00083 
00084     # Regular expression and replacement function used to transform
00085     # "a?b:c" to "b if a else c".
00086     expr = re.compile(r'(.*?)\?(.*?):(.*)')
00087     def repl(x):
00088         return "(%s if %s else %s)" % (x.group(2), x.group(1),
00089                                        expr.sub(repl, x.group(3)))
00090 
00091     # Code to transform the plural expression, taking care of parentheses
00092     stack = ['']
00093     for c in plural:
00094         if c == '(':
00095             stack.append('')
00096         elif c == ')':
00097             if len(stack) == 1:
00098                 # Actually, we never reach this code, because unbalanced
00099                 # parentheses get caught in the security check at the
00100                 # beginning.
00101                 raise ValueError('unbalanced parenthesis in plural form')
00102             s = expr.sub(repl, stack.pop())
00103             stack[-1] += '(%s)' % s
00104         else:
00105             stack[-1] += c
00106     plural = expr.sub(repl, stack.pop())
00107 
00108     return eval('lambda n: int(%s)' % plural)
00109 
00110 

Here is the call graph for this function:

Here is the caller graph for this function:

def gettext.dgettext (   domain,
  message 
)

Definition at line 459 of file gettext.py.

00459 
00460 def dgettext(domain, message):
00461     try:
00462         t = translation(domain, _localedirs.get(domain, None),
00463                         codeset=_localecodesets.get(domain))
00464     except IOError:
00465         return message
00466     return t.gettext(message)

Here is the call graph for this function:

Here is the caller graph for this function:

def gettext.dngettext (   domain,
  msgid1,
  msgid2,
  n 
)

Definition at line 475 of file gettext.py.

00475 
00476 def dngettext(domain, msgid1, msgid2, n):
00477     try:
00478         t = translation(domain, _localedirs.get(domain, None),
00479                         codeset=_localecodesets.get(domain))
00480     except IOError:
00481         if n == 1:
00482             return msgid1
00483         else:
00484             return msgid2
00485     return t.ngettext(msgid1, msgid2, n)

Here is the call graph for this function:

Here is the caller graph for this function:

def gettext.find (   domain,
  localedir = None,
  languages = None,
  all = False 
)

Definition at line 353 of file gettext.py.

00353 
00354 def find(domain, localedir=None, languages=None, all=False):
00355     # Get some reasonable defaults for arguments that were not supplied
00356     if localedir is None:
00357         localedir = _default_localedir
00358     if languages is None:
00359         languages = []
00360         for envar in ('LANGUAGE', 'LC_ALL', 'LC_MESSAGES', 'LANG'):
00361             val = os.environ.get(envar)
00362             if val:
00363                 languages = val.split(':')
00364                 break
00365         if 'C' not in languages:
00366             languages.append('C')
00367     # now normalize and expand the languages
00368     nelangs = []
00369     for lang in languages:
00370         for nelang in _expand_lang(lang):
00371             if nelang not in nelangs:
00372                 nelangs.append(nelang)
00373     # select a language
00374     if all:
00375         result = []
00376     else:
00377         result = None
00378     for lang in nelangs:
00379         if lang == 'C':
00380             break
00381         mofile = os.path.join(localedir, lang, 'LC_MESSAGES', '%s.mo' % domain)
00382         if os.path.exists(mofile):
00383             if all:
00384                 result.append(mofile)
00385             else:
00386                 return mofile
00387     return result
00388 
00389 
00390 
# a mapping between absolute .mo file path and Translation object

Here is the call graph for this function:

Here is the caller graph for this function:

def gettext.gettext (   message)

Definition at line 497 of file gettext.py.

00497 
00498 def gettext(message):
00499     return dgettext(_current_domain, message)

Here is the call graph for this function:

def gettext.install (   domain,
  localedir = None,
  codeset = None,
  names = None 
)

Definition at line 424 of file gettext.py.

00424 
00425 def install(domain, localedir=None, codeset=None, names=None):
00426     t = translation(domain, localedir, fallback=True, codeset=codeset)
00427     t.install(names)
00428 
00429 
00430 
# a mapping b/w domains and locale directories

Here is the call graph for this function:

def gettext.ldgettext (   domain,
  message 
)

Definition at line 467 of file gettext.py.

00467 
00468 def ldgettext(domain, message):
00469     try:
00470         t = translation(domain, _localedirs.get(domain, None),
00471                         codeset=_localecodesets.get(domain))
00472     except IOError:
00473         return message
00474     return t.lgettext(message)

Here is the call graph for this function:

Here is the caller graph for this function:

def gettext.ldngettext (   domain,
  msgid1,
  msgid2,
  n 
)

Definition at line 486 of file gettext.py.

00486 
00487 def ldngettext(domain, msgid1, msgid2, n):
00488     try:
00489         t = translation(domain, _localedirs.get(domain, None),
00490                         codeset=_localecodesets.get(domain))
00491     except IOError:
00492         if n == 1:
00493             return msgid1
00494         else:
00495             return msgid2
00496     return t.lngettext(msgid1, msgid2, n)

Here is the call graph for this function:

Here is the caller graph for this function:

def gettext.lgettext (   message)

Definition at line 500 of file gettext.py.

00500 
00501 def lgettext(message):
00502     return ldgettext(_current_domain, message)

Here is the call graph for this function:

def gettext.lngettext (   msgid1,
  msgid2,
  n 
)

Definition at line 506 of file gettext.py.

00506 
00507 def lngettext(msgid1, msgid2, n):
00508     return ldngettext(_current_domain, msgid1, msgid2, n)
00509 
00510 # dcgettext() has been deemed unnecessary and is not implemented.
00511 
00512 # James Henstridge's Catalog constructor from GNOME gettext.  Documented usage
00513 # was:
00514 #
00515 #    import gettext
00516 #    cat = gettext.Catalog(PACKAGE, localedir=LOCALEDIR)
00517 #    _ = cat.gettext
00518 #    print _('Hello World')
00519 
00520 # The resulting catalog object currently don't support access through a
00521 # dictionary API, which was supported (but apparently unused) in GNOME
00522 # gettext.

Here is the call graph for this function:

def gettext.ngettext (   msgid1,
  msgid2,
  n 
)

Definition at line 503 of file gettext.py.

00503 
00504 def ngettext(msgid1, msgid2, n):
00505     return dngettext(_current_domain, msgid1, msgid2, n)

Here is the call graph for this function:

Here is the caller graph for this function:

def gettext.textdomain (   domain = None)

Definition at line 438 of file gettext.py.

00438 
00439 def textdomain(domain=None):
00440     global _current_domain
00441     if domain is not None:
00442         _current_domain = domain
00443     return _current_domain
00444 

Here is the caller graph for this function:

def gettext.translation (   domain,
  localedir = None,
  languages = None,
  class_ = None,
  fallback = False,
  codeset = None 
)

Definition at line 394 of file gettext.py.

00394 
00395                 class_=None, fallback=False, codeset=None):
00396     if class_ is None:
00397         class_ = GNUTranslations
00398     mofiles = find(domain, localedir, languages, all=True)
00399     if not mofiles:
00400         if fallback:
00401             return NullTranslations()
00402         raise IOError(ENOENT, 'No translation file found for domain', domain)
00403     # Avoid opening, reading, and parsing the .mo file after it's been done
00404     # once.
00405     result = None
00406     for mofile in mofiles:
00407         key = (class_, os.path.abspath(mofile))
00408         t = _translations.get(key)
00409         if t is None:
00410             with open(mofile, 'rb') as fp:
00411                 t = _translations.setdefault(key, class_(fp))
00412         # Copy the translation object to allow setting fallbacks and
00413         # output charset. All other instance data is shared with the
00414         # cached object.
00415         t = copy.copy(t)
00416         if codeset:
00417             t.set_output_charset(codeset)
00418         if result is None:
00419             result = t
00420         else:
00421             result.add_fallback(t)
00422     return result
00423 

Here is the call graph for this function:

Here is the caller graph for this function:


Variable Documentation

Initial value:
00001 ['NullTranslations', 'GNUTranslations', 'Catalog',
00002            'find', 'translation', 'install', 'textdomain', 'bindtextdomain',
00003            'dgettext', 'dngettext', 'gettext', 'ngettext',
00004            ]

Definition at line 53 of file gettext.py.

Definition at line 435 of file gettext.py.

tuple gettext._default_localedir = os.path.join(sys.prefix, 'share', 'locale')

Definition at line 58 of file gettext.py.

Definition at line 433 of file gettext.py.

Definition at line 431 of file gettext.py.

Definition at line 391 of file gettext.py.

Definition at line 523 of file gettext.py.