1 """Internationalization and localization support.
3 This module provides internationalization (I18N) and localization (L10N)
4 support for your Python programs by providing an interface to the GNU gettext
5 message catalog library.
7 I18N refers to the operation by which a program is made aware of multiple
8 languages. L10N refers to the adaptation of your program, once
9 internationalized, to the local language and cultural habits.
13 # This module represents the integration of work, contributions, feedback, and
14 # suggestions from the following people:
16 # Martin von Loewis, who wrote the initial implementation of the underlying
17 # C-based libintlmodule (later renamed _gettext), along with a skeletal
18 # gettext.py implementation.
20 # Peter Funk, who wrote fintl.py, a fairly complete wrapper around intlmodule,
21 # which also included a pure-Python implementation to read .mo files if
22 # intlmodule wasn't available.
24 # James Henstridge, who also wrote a gettext.py module, which has some
25 # interesting, but currently unsupported experimental features: the notion of
26 # a Catalog class and instances, and the ability to add to a catalog file via
29 # Barry Warsaw integrated these modules, wrote the .install() API and code,
30 # and conformed all C and Python code to Python's coding standards.
32 # Francois Pinard and Marc-Andre Lemburg also contributed valuably to this
36 # - Lazy loading of .mo files. Currently the entire catalog is loaded into
37 # memory, but that's probably bad for large translated programs. Instead,
38 # the lexical sort of original strings in GNU .mo files should be exploited
39 # to do binary searches and lazy initializations. Or you might want to use
40 # the undocumented double-hash algorithm for .mo files with hash tables, but
41 # you'll need to study the GNU gettext code to do this.
43 # - Support Solaris .mo file formats. Unfortunately, we've been unable to
44 # find this format documented anywhere.
50 from errno
import ENOENT
52 __all__
= ["bindtextdomain","textdomain","gettext","dgettext",
53 "find","translation","install","Catalog"]
55 _default_localedir
= os
.path
.join(sys
.prefix
, 'share', 'locale')
59 def _expand_lang(locale
):
60 from locale
import normalize
61 locale
= normalize(locale
)
62 COMPONENT_CODESET
= 1 << 0
63 COMPONENT_TERRITORY
= 1 << 1
64 COMPONENT_MODIFIER
= 1 << 2
65 # split up the locale into its base components
67 pos
= locale
.find('@')
69 modifier
= locale
[pos
:]
71 mask |
= COMPONENT_MODIFIER
74 pos
= locale
.find('.')
76 codeset
= locale
[pos
:]
78 mask |
= COMPONENT_CODESET
81 pos
= locale
.find('_')
83 territory
= locale
[pos
:]
85 mask |
= COMPONENT_TERRITORY
90 for i
in range(mask
+1):
91 if not (i
& ~mask
): # if all components for this combo exist ...
93 if i
& COMPONENT_TERRITORY
: val
+= territory
94 if i
& COMPONENT_CODESET
: val
+= codeset
95 if i
& COMPONENT_MODIFIER
: val
+= modifier
102 class NullTranslations
:
103 def __init__(self
, fp
=None):
106 self
._fallback
= None
110 def _parse(self
, fp
):
113 def add_fallback(self
, fallback
):
115 self
._fallback
.add_fallback(fallback
)
117 self
._fallback
= fallback
119 def gettext(self
, message
):
121 return self
._fallback
.gettext(message
)
124 def ugettext(self
, message
):
126 return self
._fallback
.ugettext(message
)
127 return unicode(message
)
135 def install(self
, unicode=0):
137 __builtin__
.__dict
__['_'] = unicode and self
.ugettext
or self
.gettext
140 class GNUTranslations(NullTranslations
):
141 # Magic number of .mo files
142 LE_MAGIC
= 0x950412deL
143 BE_MAGIC
= 0xde120495L
145 def _parse(self
, fp
):
146 """Override this method to support alternative .mo formats."""
147 unpack
= struct
.unpack
148 filename
= getattr(fp
, 'name', '')
149 # Parse the .mo file header, which consists of 5 little endian 32
151 self
._catalog
= catalog
= {}
154 # Are we big endian or little endian?
155 magic
= unpack('<I', buf
[:4])[0]
156 if magic
== self
.LE_MAGIC
:
157 version
, msgcount
, masteridx
, transidx
= unpack('<4I', buf
[4:20])
159 elif magic
== self
.BE_MAGIC
:
160 version
, msgcount
, masteridx
, transidx
= unpack('>4I', buf
[4:20])
163 raise IOError(0, 'Bad magic number', filename
)
164 # Now put all messages from the .mo file buffer into the catalog
166 for i
in xrange(0, msgcount
):
167 mlen
, moff
= unpack(ii
, buf
[masteridx
:masteridx
+8])
169 tlen
, toff
= unpack(ii
, buf
[transidx
:transidx
+8])
171 if mend
< buflen
and tend
< buflen
:
172 tmsg
= buf
[toff
:tend
]
173 catalog
[buf
[moff
:mend
]] = tmsg
175 raise IOError(0, 'File is corrupt', filename
)
176 # See if we're looking at GNU .mo conventions for metadata
177 if mlen
== 0 and tmsg
.lower().startswith('project-id-version:'):
178 # Catalog description
179 for item
in tmsg
.split('\n'):
183 k
, v
= item
.split(':', 1)
184 k
= k
.strip().lower()
187 if k
== 'content-type':
188 self
._charset
= v
.split('charset=')[1]
189 # advance to next entry in the seek tables
193 def gettext(self
, message
):
195 return self
._catalog
[message
]
198 return self
._fallback
.gettext(message
)
201 def ugettext(self
, message
):
203 tmsg
= self
._catalog
[message
]
206 return self
._fallback
.ugettext(message
)
208 return unicode(tmsg
, self
._charset
)
212 # Locate a .mo file using the gettext strategy
213 def find(domain
, localedir
=None, languages
=None, all
=0):
214 # Get some reasonable defaults for arguments that were not supplied
215 if localedir
is None:
216 localedir
= _default_localedir
217 if languages
is None:
219 for envar
in ('LANGUAGE', 'LC_ALL', 'LC_MESSAGES', 'LANG'):
220 val
= os
.environ
.get(envar
)
222 languages
= val
.split(':')
224 if 'C' not in languages
:
225 languages
.append('C')
226 # now normalize and expand the languages
228 for lang
in languages
:
229 for nelang
in _expand_lang(lang
):
230 if nelang
not in nelangs
:
231 nelangs
.append(nelang
)
240 mofile
= os
.path
.join(localedir
, lang
, 'LC_MESSAGES', '%s.mo' % domain
)
241 if os
.path
.exists(mofile
):
243 result
.append(mofile
)
250 # a mapping between absolute .mo file path and Translation object
253 def translation(domain
, localedir
=None, languages
=None,
254 class_
=None, fallback
=0):
256 class_
= GNUTranslations
257 mofiles
= find(domain
, localedir
, languages
, all
=1)
260 return NullTranslations()
261 raise IOError(ENOENT
, 'No translation file found for domain', domain
)
262 # TBD: do we need to worry about the file pointer getting collected?
263 # Avoid opening, reading, and parsing the .mo file after it's been done
266 for mofile
in mofiles
:
267 key
= os
.path
.abspath(mofile
)
268 t
= _translations
.get(key
)
270 t
= _translations
.setdefault(key
, class_(open(mofile
, 'rb')))
271 # Copy the translation object to allow setting fallbacks.
272 # All other instance data is shared with the cached object.
277 result
.add_fallback(t
)
281 def install(domain
, localedir
=None, unicode=0):
282 translation(domain
, localedir
, fallback
=1).install(unicode)
286 # a mapping b/w domains and locale directories
288 # current global domain, `messages' used for compatibility w/ GNU gettext
289 _current_domain
= 'messages'
292 def textdomain(domain
=None):
293 global _current_domain
294 if domain
is not None:
295 _current_domain
= domain
296 return _current_domain
299 def bindtextdomain(domain
, localedir
=None):
301 if localedir
is not None:
302 _localedirs
[domain
] = localedir
303 return _localedirs
.get(domain
, _default_localedir
)
306 def dgettext(domain
, message
):
308 t
= translation(domain
, _localedirs
.get(domain
, None))
311 return t
.gettext(message
)
314 def gettext(message
):
315 return dgettext(_current_domain
, message
)
318 # dcgettext() has been deemed unnecessary and is not implemented.
320 # James Henstridge's Catalog constructor from GNOME gettext. Documented usage
324 # cat = gettext.Catalog(PACKAGE, localedir=LOCALEDIR)
326 # print _('Hello World')
328 # The resulting catalog object currently don't support access through a
329 # dictionary API, which was supported (but apparently unused) in GNOME
332 Catalog
= translation