/
usr
/
share
/
doc
/
python3-docs
/
html
/
_sources
/
library
/
/usr/share/doc/python3-docs/html/_sources/library
mkdir
upload
Name
Size
Mode
Actions
2to3.rst.txt
15898
0644
edit
dl
rm
abc.rst.txt
11805
0644
edit
dl
rm
aifc.rst.txt
7503
0644
edit
dl
rm
allos.rst.txt
678
0644
edit
dl
rm
archiving.rst.txt
440
0644
edit
dl
rm
argparse.rst.txt
77480
0644
edit
dl
rm
array.rst.txt
10812
0644
edit
dl
rm
ast.rst.txt
10159
0644
edit
dl
rm
asynchat.rst.txt
8528
0644
edit
dl
rm
asyncio-dev.rst.txt
13398
0644
edit
dl
rm
asyncio-eventloop.rst.txt
33701
0644
edit
dl
rm
asyncio-eventloops.rst.txt
7660
0644
edit
dl
rm
asyncio-protocol.rst.txt
25170
0644
edit
dl
rm
asyncio-queue.rst.txt
4328
0644
edit
dl
rm
asyncio-stream.rst.txt
14363
0644
edit
dl
rm
asyncio-subprocess.rst.txt
15544
0644
edit
dl
rm
asyncio-sync.rst.txt
9078
0644
edit
dl
rm
asyncio-task.rst.txt
25406
0644
edit
dl
rm
asyncio.rst.txt
2272
0644
edit
dl
rm
asyncore.rst.txt
13624
0644
edit
dl
rm
atexit.rst.txt
3669
0644
edit
dl
rm
audioop.rst.txt
10712
0644
edit
dl
rm
base64.rst.txt
10371
0644
edit
dl
rm
bdb.rst.txt
12985
0644
edit
dl
rm
binary.rst.txt
654
0644
edit
dl
rm
binascii.rst.txt
6539
0644
edit
dl
rm
binhex.rst.txt
1709
0644
edit
dl
rm
bisect.rst.txt
5398
0644
edit
dl
rm
builtins.rst.txt
1465
0644
edit
dl
rm
bz2.rst.txt
8825
0644
edit
dl
rm
calendar.rst.txt
10988
0644
edit
dl
rm
cgi.rst.txt
22650
0644
edit
dl
rm
cgitb.rst.txt
2918
0644
edit
dl
rm
chunk.rst.txt
5094
0644
edit
dl
rm
cmath.rst.txt
9326
0644
edit
dl
rm
cmd.rst.txt
13795
0644
edit
dl
rm
code.rst.txt
7817
0644
edit
dl
rm
codecs.rst.txt
75564
0644
edit
dl
rm
codeop.rst.txt
3021
0644
edit
dl
rm
collections.abc.rst.txt
12861
0644
edit
dl
rm
collections.rst.txt
46063
0644
edit
dl
rm
colorsys.rst.txt
1820
0644
edit
dl
rm
compileall.rst.txt
8975
0644
edit
dl
rm
concurrency.rst.txt
673
0644
edit
dl
rm
concurrent.futures.rst.txt
16910
0644
edit
dl
rm
concurrent.rst.txt
171
0644
edit
dl
rm
configparser.rst.txt
48756
0644
edit
dl
rm
constants.rst.txt
3331
0644
edit
dl
rm
contextlib.rst.txt
28175
0644
edit
dl
rm
copy.rst.txt
3378
0644
edit
dl
rm
copyreg.rst.txt
2182
0644
edit
dl
rm
crypt.rst.txt
5122
0644
edit
dl
rm
crypto.rst.txt
411
0644
edit
dl
rm
csv.rst.txt
19902
0644
edit
dl
rm
ctypes.rst.txt
88613
0644
edit
dl
rm
curses.ascii.rst.txt
8920
0644
edit
dl
rm
curses.panel.rst.txt
2764
0644
edit
dl
rm
curses.rst.txt
76397
0644
edit
dl
rm
custominterp.rst.txt
569
0644
edit
dl
rm
datatypes.rst.txt
751
0644
edit
dl
rm
datetime.rst.txt
90524
0644
edit
dl
rm
dbm.rst.txt
14293
0644
edit
dl
rm
debug.rst.txt
471
0644
edit
dl
rm
decimal.rst.txt
74869
0644
edit
dl
rm
development.rst.txt
704
0644
edit
dl
rm
difflib.rst.txt
29861
0644
edit
dl
rm
dis.rst.txt
32567
0644
edit
dl
rm
distribution.rst.txt
452
0644
edit
dl
rm
distutils.rst.txt
1974
0644
edit
dl
rm
doctest.rst.txt
71743
0644
edit
dl
rm
dummy_threading.rst.txt
784
0644
edit
dl
rm
email.charset.rst.txt
9293
0644
edit
dl
rm
email.compat32-message.rst.txt
33493
0644
edit
dl
rm
email.contentmanager.rst.txt
9112
0644
edit
dl
rm
email.encoders.rst.txt
2715
0644
edit
dl
rm
email.errors.rst.txt
4792
0644
edit
dl
rm
email.examples.rst.txt
1915
0644
edit
dl
rm
email.generator.rst.txt
13637
0644
edit
dl
rm
email.header.rst.txt
9188
0644
edit
dl
rm
email.headerregistry.rst.txt
17957
0644
edit
dl
rm
email.iterators.rst.txt
2795
0644
edit
dl
rm
email.message.rst.txt
33008
0644
edit
dl
rm
email.mime.rst.txt
11721
0644
edit
dl
rm
email.parser.rst.txt
14092
0644
edit
dl
rm
email.policy.rst.txt
27022
0644
edit
dl
rm
email.rst.txt
6785
0644
edit
dl
rm
email.util.rst.txt
9214
0644
edit
dl
rm
ensurepip.rst.txt
4987
0644
edit
dl
rm
enum.rst.txt
32751
0644
edit
dl
rm
errno.rst.txt
6811
0644
edit
dl
rm
exceptions.rst.txt
25570
0644
edit
dl
rm
faulthandler.rst.txt
6136
0644
edit
dl
rm
fcntl.rst.txt
7152
0644
edit
dl
rm
filecmp.rst.txt
5623
0644
edit
dl
rm
fileformats.rst.txt
287
0644
edit
dl
rm
fileinput.rst.txt
8051
0644
edit
dl
rm
filesys.rst.txt
961
0644
edit
dl
rm
fnmatch.rst.txt
3103
0644
edit
dl
rm
formatter.rst.txt
13242
0644
edit
dl
rm
fpectl.rst.txt
4180
0644
edit
dl
rm
fractions.rst.txt
6364
0644
edit
dl
rm
frameworks.rst.txt
391
0644
edit
dl
rm
ftplib.rst.txt
17552
0644
edit
dl
rm
functional.rst.txt
365
0644
edit
dl
rm
functions.rst.txt
71621
0644
edit
dl
rm
functools.rst.txt
18503
0644
edit
dl
rm
gc.rst.txt
9694
0644
edit
dl
rm
getopt.rst.txt
6557
0644
edit
dl
rm
getpass.rst.txt
1882
0644
edit
dl
rm
gettext.rst.txt
25588
0644
edit
dl
rm
glob.rst.txt
3508
0644
edit
dl
rm
grp.rst.txt
2417
0644
edit
dl
rm
gzip.rst.txt
8301
0644
edit
dl
rm
hashlib.rst.txt
26523
0644
edit
dl
rm
heapq.rst.txt
13402
0644
edit
dl
rm
hmac.rst.txt
4020
0644
edit
dl
rm
html.entities.rst.txt
1319
0644
edit
dl
rm
html.parser.rst.txt
11275
0644
edit
dl
rm
html.rst.txt
1304
0644
edit
dl
rm
http.client.rst.txt
18870
0644
edit
dl
rm
http.cookiejar.rst.txt
27832
0644
edit
dl
rm
http.cookies.rst.txt
8645
0644
edit
dl
rm
http.rst.txt
7096
0644
edit
dl
rm
http.server.rst.txt
17639
0644
edit
dl
rm
i18n.rst.txt
408
0644
edit
dl
rm
idle.rst.txt
25834
0644
edit
dl
rm
imaplib.rst.txt
20367
0644
edit
dl
rm
imghdr.rst.txt
2938
0644
edit
dl
rm
imp.rst.txt
15548
0644
edit
dl
rm
importlib.rst.txt
53563
0644
edit
dl
rm
index.rst.txt
2258
0644
edit
dl
rm
inspect.rst.txt
53928
0644
edit
dl
rm
internet.rst.txt
992
0644
edit
dl
rm
intro.rst.txt
2645
0644
edit
dl
rm
io.rst.txt
40328
0644
edit
dl
rm
ipaddress.rst.txt
32340
0644
edit
dl
rm
ipc.rst.txt
649
0644
edit
dl
rm
itertools.rst.txt
38459
0644
edit
dl
rm
json.rst.txt
27876
0644
edit
dl
rm
keyword.rst.txt
617
0644
edit
dl
rm
language.rst.txt
522
0644
edit
dl
rm
linecache.rst.txt
2408
0644
edit
dl
rm
locale.rst.txt
25470
0644
edit
dl
rm
logging.config.rst.txt
33886
0644
edit
dl
rm
logging.handlers.rst.txt
42497
0644
edit
dl
rm
logging.rst.txt
60479
0644
edit
dl
rm
lzma.rst.txt
17361
0644
edit
dl
rm
macpath.rst.txt
707
0644
edit
dl
rm
mailbox.rst.txt
63055
0644
edit
dl
rm
mailcap.rst.txt
3691
0644
edit
dl
rm
markup.rst.txt
679
0644
edit
dl
rm
marshal.rst.txt
4855
0644
edit
dl
rm
math.rst.txt
14375
0644
edit
dl
rm
mimetypes.rst.txt
9839
0644
edit
dl
rm
misc.rst.txt
247
0644
edit
dl
rm
mm.rst.txt
431
0644
edit
dl
rm
mmap.rst.txt
11232
0644
edit
dl
rm
modulefinder.rst.txt
3240
0644
edit
dl
rm
modules.rst.txt
355
0644
edit
dl
rm
msilib.rst.txt
18612
0644
edit
dl
rm
msvcrt.rst.txt
4392
0644
edit
dl
rm
multiprocessing.rst.txt
104494
0644
edit
dl
rm
netdata.rst.txt
339
0644
edit
dl
rm
netrc.rst.txt
3007
0644
edit
dl
rm
nis.rst.txt
1993
0644
edit
dl
rm
nntplib.rst.txt
21821
0644
edit
dl
rm
numbers.rst.txt
8089
0644
edit
dl
rm
numeric.rst.txt
696
0644
edit
dl
rm
operator.rst.txt
18989
0644
edit
dl
rm
optparse.rst.txt
76996
0644
edit
dl
rm
os.path.rst.txt
16419
0644
edit
dl
rm
os.rst.txt
137534
0644
edit
dl
rm
ossaudiodev.rst.txt
17845
0644
edit
dl
rm
othergui.rst.txt
2822
0644
edit
dl
rm
parser.rst.txt
15148
0644
edit
dl
rm
pathlib.rst.txt
30045
0644
edit
dl
rm
pdb.rst.txt
19454
0644
edit
dl
rm
persistence.rst.txt
591
0644
edit
dl
rm
pickle.rst.txt
37440
0644
edit
dl
rm
pickletools.rst.txt
3729
0644
edit
dl
rm
pipes.rst.txt
2557
0644
edit
dl
rm
pkgutil.rst.txt
8730
0644
edit
dl
rm
platform.rst.txt
9624
0644
edit
dl
rm
plistlib.rst.txt
7398
0644
edit
dl
rm
poplib.rst.txt
8197
0644
edit
dl
rm
posix.rst.txt
3694
0644
edit
dl
rm
pprint.rst.txt
14274
0644
edit
dl
rm
profile.rst.txt
27969
0644
edit
dl
rm
pty.rst.txt
3123
0644
edit
dl
rm
pwd.rst.txt
2739
0644
edit
dl
rm
pyclbr.rst.txt
3297
0644
edit
dl
rm
pydoc.rst.txt
4688
0644
edit
dl
rm
pyexpat.rst.txt
28620
0644
edit
dl
rm
python.rst.txt
475
0644
edit
dl
rm
py_compile.rst.txt
3851
0644
edit
dl
rm
queue.rst.txt
7268
0644
edit
dl
rm
quopri.rst.txt
2571
0644
edit
dl
rm
random.rst.txt
18503
0644
edit
dl
rm
re.rst.txt
64936
0644
edit
dl
rm
readline.rst.txt
11943
0644
edit
dl
rm
reprlib.rst.txt
5162
0644
edit
dl
rm
resource.rst.txt
12291
0644
edit
dl
rm
rlcompleter.rst.txt
2294
0644
edit
dl
rm
runpy.rst.txt
8285
0644
edit
dl
rm
sched.rst.txt
4842
0644
edit
dl
rm
secrets.rst.txt
5930
0644
edit
dl
rm
select.rst.txt
28175
0644
edit
dl
rm
selectors.rst.txt
8925
0644
edit
dl
rm
shelve.rst.txt
8390
0644
edit
dl
rm
shlex.rst.txt
16441
0644
edit
dl
rm
shutil.rst.txt
26014
0644
edit
dl
rm
signal.rst.txt
17218
0644
edit
dl
rm
site.rst.txt
9628
0644
edit
dl
rm
smtpd.rst.txt
10806
0644
edit
dl
rm
smtplib.rst.txt
23439
0644
edit
dl
rm
sndhdr.rst.txt
1994
0644
edit
dl
rm
socket.rst.txt
68202
0644
edit
dl
rm
socketserver.rst.txt
23712
0644
edit
dl
rm
spwd.rst.txt
2958
0644
edit
dl
rm
sqlite3.rst.txt
39215
0644
edit
dl
rm
ssl.rst.txt
96021
0644
edit
dl
rm
stat.rst.txt
9805
0644
edit
dl
rm
statistics.rst.txt
15301
0644
edit
dl
rm
stdtypes.rst.txt
179240
0644
edit
dl
rm
string.rst.txt
35374
0644
edit
dl
rm
stringprep.rst.txt
4279
0644
edit
dl
rm
struct.rst.txt
19581
0644
edit
dl
rm
subprocess.rst.txt
45793
0644
edit
dl
rm
sunau.rst.txt
7390
0644
edit
dl
rm
superseded.rst.txt
258
0644
edit
dl
rm
symbol.rst.txt
975
0644
edit
dl
rm
symtable.rst.txt
4964
0644
edit
dl
rm
sys.rst.txt
58273
0644
edit
dl
rm
sysconfig.rst.txt
8749
0644
edit
dl
rm
syslog.rst.txt
4302
0644
edit
dl
rm
tabnanny.rst.txt
2007
0644
edit
dl
rm
tarfile.rst.txt
31749
0644
edit
dl
rm
telnetlib.rst.txt
7899
0644
edit
dl
rm
tempfile.rst.txt
13857
0644
edit
dl
rm
termios.rst.txt
3751
0644
edit
dl
rm
test.rst.txt
25764
0644
edit
dl
rm
text.rst.txt
584
0644
edit
dl
rm
textwrap.rst.txt
10519
0644
edit
dl
rm
threading.rst.txt
39257
0644
edit
dl
rm
time.rst.txt
32967
0644
edit
dl
rm
timeit.rst.txt
13000
0644
edit
dl
rm
tk.rst.txt
1639
0644
edit
dl
rm
tkinter.rst.txt
33027
0644
edit
dl
rm
tkinter.scrolledtext.rst.txt
1255
0644
edit
dl
rm
tkinter.tix.rst.txt
22653
0644
edit
dl
rm
tkinter.ttk.rst.txt
58489
0644
edit
dl
rm
token.rst.txt
2607
0644
edit
dl
rm
tokenize.rst.txt
10002
0644
edit
dl
rm
trace.rst.txt
6914
0644
edit
dl
rm
traceback.rst.txt
17854
0644
edit
dl
rm
tracemalloc.rst.txt
22089
0644
edit
dl
rm
tty.rst.txt
1097
0644
edit
dl
rm
turtle.rst.txt
71221
0644
edit
dl
rm
types.rst.txt
9999
0644
edit
dl
rm
typing.rst.txt
34332
0644
edit
dl
rm
undoc.rst.txt
780
0644
edit
dl
rm
unicodedata.rst.txt
5762
0644
edit
dl
rm
unittest.mock-examples.rst.txt
46206
0644
edit
dl
rm
unittest.mock.rst.txt
85991
0644
edit
dl
rm
unittest.rst.txt
93304
0644
edit
dl
rm
unix.rst.txt
446
0644
edit
dl
rm
urllib.error.rst.txt
2199
0644
edit
dl
rm
urllib.parse.rst.txt
27332
0644
edit
dl
rm
urllib.request.rst.txt
59360
0644
edit
dl
rm
urllib.robotparser.rst.txt
2969
0644
edit
dl
rm
urllib.rst.txt
466
0644
edit
dl
rm
uu.rst.txt
2387
0644
edit
dl
rm
uuid.rst.txt
8760
0644
edit
dl
rm
venv.rst.txt
20621
0644
edit
dl
rm
warnings.rst.txt
20152
0644
edit
dl
rm
wave.rst.txt
6870
0644
edit
dl
rm
weakref.rst.txt
21328
0644
edit
dl
rm
webbrowser.rst.txt
9783
0644
edit
dl
rm
windows.rst.txt
272
0644
edit
dl
rm
winreg.rst.txt
24073
0644
edit
dl
rm
winsound.rst.txt
5134
0644
edit
dl
rm
wsgiref.rst.txt
33047
0644
edit
dl
rm
xdrlib.rst.txt
8078
0644
edit
dl
rm
xml.dom.minidom.rst.txt
10198
0644
edit
dl
rm
xml.dom.pulldom.rst.txt
5186
0644
edit
dl
rm
xml.dom.rst.txt
39507
0644
edit
dl
rm
xml.etree.elementtree.rst.txt
43871
0644
edit
dl
rm
xml.rst.txt
6071
0644
edit
dl
rm
xml.sax.handler.rst.txt
15399
0644
edit
dl
rm
xml.sax.reader.rst.txt
12133
0644
edit
dl
rm
xml.sax.rst.txt
7159
0644
edit
dl
rm
xml.sax.utils.rst.txt
3901
0644
edit
dl
rm
xmlrpc.client.rst.txt
23071
0644
edit
dl
rm
xmlrpc.rst.txt
475
0644
edit
dl
rm
xmlrpc.server.rst.txt
14990
0644
edit
dl
rm
zipapp.rst.txt
17392
0644
edit
dl
rm
zipfile.rst.txt
24005
0644
edit
dl
rm
zipimport.rst.txt
5805
0644
edit
dl
rm
zlib.rst.txt
13912
0644
edit
dl
rm
_dummy_thread.rst.txt
762
0644
edit
dl
rm
_thread.rst.txt
6886
0644
edit
dl
rm
__future__.rst.txt
5245
0644
edit
dl
rm
__main__.rst.txt
904
0644
edit
dl
rm
Edit:
/usr/share/doc/python3-docs/html/_sources/library/gettext.rst.txt
(25588B)
:mod:`gettext` --- Multilingual internationalization services ============================================================= .. module:: gettext :synopsis: Multilingual internationalization services. .. moduleauthor:: Barry A. Warsaw <barry@python.org> .. sectionauthor:: Barry A. Warsaw <barry@python.org> **Source code:** :source:`Lib/gettext.py` -------------- The :mod:`gettext` module provides internationalization (I18N) and localization (L10N) services for your Python modules and applications. It supports both the GNU ``gettext`` message catalog API and a higher level, class-based API that may be more appropriate for Python files. The interface described below allows you to write your module and application messages in one natural language, and provide a catalog of translated messages for running under different natural languages. Some hints on localizing your Python modules and applications are also given. GNU :program:`gettext` API -------------------------- The :mod:`gettext` module defines the following API, which is very similar to the GNU :program:`gettext` API. If you use this API you will affect the translation of your entire application globally. Often this is what you want if your application is monolingual, with the choice of language dependent on the locale of your user. If you are localizing a Python module, or if your application needs to switch languages on the fly, you probably want to use the class-based API instead. .. function:: bindtextdomain(domain, localedir=None) Bind the *domain* to the locale directory *localedir*. More concretely, :mod:`gettext` will look for binary :file:`.mo` files for the given domain using the path (on Unix): :file:`localedir/language/LC_MESSAGES/domain.mo`, where *languages* is searched for in the environment variables :envvar:`LANGUAGE`, :envvar:`LC_ALL`, :envvar:`LC_MESSAGES`, and :envvar:`LANG` respectively. If *localedir* is omitted or ``None``, then the current binding for *domain* is returned. [#]_ .. function:: bind_textdomain_codeset(domain, codeset=None) Bind the *domain* to *codeset*, changing the encoding of byte strings returned by the :func:`lgettext`, :func:`ldgettext`, :func:`lngettext` and :func:`ldngettext` functions. If *codeset* is omitted, then the current binding is returned. .. function:: textdomain(domain=None) Change or query the current global domain. If *domain* is ``None``, then the current global domain is returned, otherwise the global domain is set to *domain*, which is returned. .. function:: gettext(message) Return the localized translation of *message*, based on the current global domain, language, and locale directory. This function is usually aliased as :func:`_` in the local namespace (see examples below). .. function:: dgettext(domain, message) Like :func:`.gettext`, but look the message up in the specified *domain*. .. function:: ngettext(singular, plural, n) Like :func:`.gettext`, but consider plural forms. If a translation is found, apply the plural formula to *n*, and return the resulting message (some languages have more than two plural forms). If no translation is found, return *singular* if *n* is 1; return *plural* otherwise. The Plural formula is taken from the catalog header. It is a C or Python expression that has a free variable *n*; the expression evaluates to the index of the plural in the catalog. See `the GNU gettext documentation <https://www.gnu.org/software/gettext/manual/gettext.html>`__ for the precise syntax to be used in :file:`.po` files and the formulas for a variety of languages. .. function:: dngettext(domain, singular, plural, n) Like :func:`ngettext`, but look the message up in the specified *domain*. .. function:: lgettext(message) .. function:: ldgettext(domain, message) .. function:: lngettext(singular, plural, n) .. function:: ldngettext(domain, singular, plural, n) Equivalent to the corresponding functions without the ``l`` prefix (:func:`.gettext`, :func:`dgettext`, :func:`ngettext` and :func:`dngettext`), but the translation is returned as a byte string encoded in the preferred system encoding if no other encoding was explicitly set with :func:`bind_textdomain_codeset`. .. warning:: These functions should be avoided in Python 3, because they return encoded bytes. It's much better to use alternatives which return Unicode strings instead, since most Python applications will want to manipulate human readable text as strings instead of bytes. Further, it's possible that you may get unexpected Unicode-related exceptions if there are encoding problems with the translated strings. It is possible that the ``l*()`` functions will be deprecated in future Python versions due to their inherent problems and limitations. Note that GNU :program:`gettext` also defines a :func:`dcgettext` method, but this was deemed not useful and so it is currently unimplemented. Here's an example of typical usage for this API:: import gettext gettext.bindtextdomain('myapplication', '/path/to/my/language/directory') gettext.textdomain('myapplication') _ = gettext.gettext # ... print(_('This is a translatable string.')) Class-based API --------------- The class-based API of the :mod:`gettext` module gives you more flexibility and greater convenience than the GNU :program:`gettext` API. It is the recommended way of localizing your Python applications and modules. :mod:`!gettext` defines a "translations" class which implements the parsing of GNU :file:`.mo` format files, and has methods for returning strings. Instances of this "translations" class can also install themselves in the built-in namespace as the function :func:`_`. .. function:: find(domain, localedir=None, languages=None, all=False) This function implements the standard :file:`.mo` file search algorithm. It takes a *domain*, identical to what :func:`textdomain` takes. Optional *localedir* is as in :func:`bindtextdomain` Optional *languages* is a list of strings, where each string is a language code. If *localedir* is not given, then the default system locale directory is used. [#]_ If *languages* is not given, then the following environment variables are searched: :envvar:`LANGUAGE`, :envvar:`LC_ALL`, :envvar:`LC_MESSAGES`, and :envvar:`LANG`. The first one returning a non-empty value is used for the *languages* variable. The environment variables should contain a colon separated list of languages, which will be split on the colon to produce the expected list of language code strings. :func:`find` then expands and normalizes the languages, and then iterates through them, searching for an existing file built of these components: :file:`{localedir}/{language}/LC_MESSAGES/{domain}.mo` The first such file name that exists is returned by :func:`find`. If no such file is found, then ``None`` is returned. If *all* is given, it returns a list of all file names, in the order in which they appear in the languages list or the environment variables. .. function:: translation(domain, localedir=None, languages=None, class_=None, fallback=False, codeset=None) Return a :class:`Translations` instance based on the *domain*, *localedir*, and *languages*, which are first passed to :func:`find` to get a list of the associated :file:`.mo` file paths. Instances with identical :file:`.mo` file names are cached. The actual class instantiated is either *class_* if provided, otherwise :class:`GNUTranslations`. The class's constructor must take a single :term:`file object` argument. If provided, *codeset* will change the charset used to encode translated strings in the :meth:`~NullTranslations.lgettext` and :meth:`~NullTranslations.lngettext` methods. If multiple files are found, later files are used as fallbacks for earlier ones. To allow setting the fallback, :func:`copy.copy` is used to clone each translation object from the cache; the actual instance data is still shared with the cache. If no :file:`.mo` file is found, this function raises :exc:`OSError` if *fallback* is false (which is the default), and returns a :class:`NullTranslations` instance if *fallback* is true. .. versionchanged:: 3.3 :exc:`IOError` used to be raised instead of :exc:`OSError`. .. function:: install(domain, localedir=None, codeset=None, names=None) This installs the function :func:`_` in Python's builtins namespace, based on *domain*, *localedir*, and *codeset* which are passed to the function :func:`translation`. For the *names* parameter, please see the description of the translation object's :meth:`~NullTranslations.install` method. As seen below, you usually mark the strings in your application that are candidates for translation, by wrapping them in a call to the :func:`_` function, like this:: print(_('This string will be translated.')) For convenience, you want the :func:`_` function to be installed in Python's builtins namespace, so it is easily accessible in all modules of your application. The :class:`NullTranslations` class ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Translation classes are what actually implement the translation of original source file message strings to translated message strings. The base class used by all translation classes is :class:`NullTranslations`; this provides the basic interface you can use to write your own specialized translation classes. Here are the methods of :class:`!NullTranslations`: .. class:: NullTranslations(fp=None) Takes an optional :term:`file object` *fp*, which is ignored by the base class. Initializes "protected" instance variables *_info* and *_charset* which are set by derived classes, as well as *_fallback*, which is set through :meth:`add_fallback`. It then calls ``self._parse(fp)`` if *fp* is not ``None``. .. method:: _parse(fp) No-op'd in the base class, this method takes file object *fp*, and reads the data from the file, initializing its message catalog. If you have an unsupported message catalog file format, you should override this method to parse your format. .. method:: add_fallback(fallback) Add *fallback* as the fallback object for the current translation object. A translation object should consult the fallback if it cannot provide a translation for a given message. .. method:: gettext(message) If a fallback has been set, forward :meth:`!gettext` to the fallback. Otherwise, return *message*. Overridden in derived classes. .. method:: ngettext(singular, plural, n) If a fallback has been set, forward :meth:`!ngettext` to the fallback. Otherwise, return *singular* if *n* is 1; return *plural* otherwise. Overridden in derived classes. .. method:: lgettext(message) .. method:: lngettext(singular, plural, n) Equivalent to :meth:`.gettext` and :meth:`.ngettext`, but the translation is returned as a byte string encoded in the preferred system encoding if no encoding was explicitly set with :meth:`set_output_charset`. Overridden in derived classes. .. warning:: These methods should be avoided in Python 3. See the warning for the :func:`lgettext` function. .. method:: info() Return the "protected" :attr:`_info` variable. .. method:: charset() Return the encoding of the message catalog file. .. method:: output_charset() Return the encoding used to return translated messages in :meth:`.lgettext` and :meth:`.lngettext`. .. method:: set_output_charset(charset) Change the encoding used to return translated messages. .. method:: install(names=None) This method installs :meth:`.gettext` into the built-in namespace, binding it to ``_``. If the *names* parameter is given, it must be a sequence containing the names of functions you want to install in the builtins namespace in addition to :func:`_`. Supported names are ``'gettext'``, ``'ngettext'``, ``'lgettext'`` and ``'lngettext'``. Note that this is only one way, albeit the most convenient way, to make the :func:`_` function available to your application. Because it affects the entire application globally, and specifically the built-in namespace, localized modules should never install :func:`_`. Instead, they should use this code to make :func:`_` available to their module:: import gettext t = gettext.translation('mymodule', ...) _ = t.gettext This puts :func:`_` only in the module's global namespace and so only affects calls within this module. The :class:`GNUTranslations` class ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ The :mod:`gettext` module provides one additional class derived from :class:`NullTranslations`: :class:`GNUTranslations`. This class overrides :meth:`_parse` to enable reading GNU :program:`gettext` format :file:`.mo` files in both big-endian and little-endian format. :class:`GNUTranslations` parses optional meta-data out of the translation catalog. It is convention with GNU :program:`gettext` to include meta-data as the translation for the empty string. This meta-data is in :rfc:`822`\ -style ``key: value`` pairs, and should contain the ``Project-Id-Version`` key. If the key ``Content-Type`` is found, then the ``charset`` property is used to initialize the "protected" :attr:`_charset` instance variable, defaulting to ``None`` if not found. If the charset encoding is specified, then all message ids and message strings read from the catalog are converted to Unicode using this encoding, else ASCII encoding is assumed. Since message ids are read as Unicode strings too, all :meth:`*gettext` methods will assume message ids as Unicode strings, not byte strings. The entire set of key/value pairs are placed into a dictionary and set as the "protected" :attr:`_info` instance variable. If the :file:`.mo` file's magic number is invalid, the major version number is unexpected, or if other problems occur while reading the file, instantiating a :class:`GNUTranslations` class can raise :exc:`OSError`. .. class:: GNUTranslations The following methods are overridden from the base class implementation: .. method:: gettext(message) Look up the *message* id in the catalog and return the corresponding message string, as a Unicode string. If there is no entry in the catalog for the *message* id, and a fallback has been set, the look up is forwarded to the fallback's :meth:`~NullTranslations.gettext` method. Otherwise, the *message* id is returned. .. method:: ngettext(singular, plural, n) Do a plural-forms lookup of a message id. *singular* is used as the message id for purposes of lookup in the catalog, while *n* is used to determine which plural form to use. The returned message string is a Unicode string. If the message id is not found in the catalog, and a fallback is specified, the request is forwarded to the fallback's :meth:`~NullTranslations.ngettext` method. Otherwise, when *n* is 1 *singular* is returned, and *plural* is returned in all other cases. Here is an example:: n = len(os.listdir('.')) cat = GNUTranslations(somefile) message = cat.ngettext( 'There is %(num)d file in this directory', 'There are %(num)d files in this directory', n) % {'num': n} .. method:: lgettext(message) .. method:: lngettext(singular, plural, n) Equivalent to :meth:`.gettext` and :meth:`.ngettext`, but the translation is returned as a byte string encoded in the preferred system encoding if no encoding was explicitly set with :meth:`~NullTranslations.set_output_charset`. .. warning:: These methods should be avoided in Python 3. See the warning for the :func:`lgettext` function. Solaris message catalog support ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ The Solaris operating system defines its own binary :file:`.mo` file format, but since no documentation can be found on this format, it is not supported at this time. The Catalog constructor ^^^^^^^^^^^^^^^^^^^^^^^ .. index:: single: GNOME GNOME uses a version of the :mod:`gettext` module by James Henstridge, but this version has a slightly different API. Its documented usage was:: import gettext cat = gettext.Catalog(domain, localedir) _ = cat.gettext print(_('hello world')) For compatibility with this older module, the function :func:`Catalog` is an alias for the :func:`translation` function described above. One difference between this module and Henstridge's: his catalog objects supported access through a mapping API, but this appears to be unused and so is not currently supported. Internationalizing your programs and modules -------------------------------------------- Internationalization (I18N) refers to the operation by which a program is made aware of multiple languages. Localization (L10N) refers to the adaptation of your program, once internationalized, to the local language and cultural habits. In order to provide multilingual messages for your Python programs, you need to take the following steps: #. prepare your program or module by specially marking translatable strings #. run a suite of tools over your marked files to generate raw messages catalogs #. create language specific translations of the message catalogs #. use the :mod:`gettext` module so that message strings are properly translated In order to prepare your code for I18N, you need to look at all the strings in your files. Any string that needs to be translated should be marked by wrapping it in ``_('...')`` --- that is, a call to the function :func:`_`. For example:: filename = 'mylog.txt' message = _('writing a log message') fp = open(filename, 'w') fp.write(message) fp.close() In this example, the string ``'writing a log message'`` is marked as a candidate for translation, while the strings ``'mylog.txt'`` and ``'w'`` are not. There are a few tools to extract the strings meant for translation. The original GNU :program:`gettext` only supported C or C++ source code but its extended version :program:`xgettext` scans code written in a number of languages, including Python, to find strings marked as translatable. `Babel <http://babel.pocoo.org/>`__ is a Python internationalization library that includes a :file:`pybabel` script to extract and compile message catalogs. François Pinard's program called :program:`xpot` does a similar job and is available as part of his `po-utils package <https://github.com/pinard/po-utils>`__. (Python also includes pure-Python versions of these programs, called :program:`pygettext.py` and :program:`msgfmt.py`; some Python distributions will install them for you. :program:`pygettext.py` is similar to :program:`xgettext`, but only understands Python source code and cannot handle other programming languages such as C or C++. :program:`pygettext.py` supports a command-line interface similar to :program:`xgettext`; for details on its use, run ``pygettext.py --help``. :program:`msgfmt.py` is binary compatible with GNU :program:`msgfmt`. With these two programs, you may not need the GNU :program:`gettext` package to internationalize your Python applications.) :program:`xgettext`, :program:`pygettext`, and similar tools generate :file:`.po` files that are message catalogs. They are structured human-readable files that contain every marked string in the source code, along with a placeholder for the translated versions of these strings. Copies of these :file:`.po` files are then handed over to the individual human translators who write translations for every supported natural language. They send back the completed language-specific versions as a :file:`<language-name>.po` file that's compiled into a machine-readable :file:`.mo` binary catalog file using the :program:`msgfmt` program. The :file:`.mo` files are used by the :mod:`gettext` module for the actual translation processing at run-time. How you use the :mod:`gettext` module in your code depends on whether you are internationalizing a single module or your entire application. The next two sections will discuss each case. Localizing your module ^^^^^^^^^^^^^^^^^^^^^^ If you are localizing your module, you must take care not to make global changes, e.g. to the built-in namespace. You should not use the GNU ``gettext`` API but instead the class-based API. Let's say your module is called "spam" and the module's various natural language translation :file:`.mo` files reside in :file:`/usr/share/locale` in GNU :program:`gettext` format. Here's what you would put at the top of your module:: import gettext t = gettext.translation('spam', '/usr/share/locale') _ = t.gettext Localizing your application ^^^^^^^^^^^^^^^^^^^^^^^^^^^ If you are localizing your application, you can install the :func:`_` function globally into the built-in namespace, usually in the main driver file of your application. This will let all your application-specific files just use ``_('...')`` without having to explicitly install it in each file. In the simple case then, you need only add the following bit of code to the main driver file of your application:: import gettext gettext.install('myapplication') If you need to set the locale directory, you can pass it into the :func:`install` function:: import gettext gettext.install('myapplication', '/usr/share/locale') Changing languages on the fly ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ If your program needs to support many languages at the same time, you may want to create multiple translation instances and then switch between them explicitly, like so:: import gettext lang1 = gettext.translation('myapplication', languages=['en']) lang2 = gettext.translation('myapplication', languages=['fr']) lang3 = gettext.translation('myapplication', languages=['de']) # start by using language1 lang1.install() # ... time goes by, user selects language 2 lang2.install() # ... more time goes by, user selects language 3 lang3.install() Deferred translations ^^^^^^^^^^^^^^^^^^^^^ In most coding situations, strings are translated where they are coded. Occasionally however, you need to mark strings for translation, but defer actual translation until later. A classic example is:: animals = ['mollusk', 'albatross', 'rat', 'penguin', 'python', ] # ... for a in animals: print(a) Here, you want to mark the strings in the ``animals`` list as being translatable, but you don't actually want to translate them until they are printed. Here is one way you can handle this situation:: def _(message): return message animals = [_('mollusk'), _('albatross'), _('rat'), _('penguin'), _('python'), ] del _ # ... for a in animals: print(_(a)) This works because the dummy definition of :func:`_` simply returns the string unchanged. And this dummy definition will temporarily override any definition of :func:`_` in the built-in namespace (until the :keyword:`del` command). Take care, though if you have a previous definition of :func:`_` in the local namespace. Note that the second use of :func:`_` will not identify "a" as being translatable to the :program:`gettext` program, because the parameter is not a string literal. Another way to handle this is with the following example:: def N_(message): return message animals = [N_('mollusk'), N_('albatross'), N_('rat'), N_('penguin'), N_('python'), ] # ... for a in animals: print(_(a)) In this case, you are marking translatable strings with the function :func:`N_`, which won't conflict with any definition of :func:`_`. However, you will need to teach your message extraction program to look for translatable strings marked with :func:`N_`. :program:`xgettext`, :program:`pygettext`, ``pybabel extract``, and :program:`xpot` all support this through the use of the :option:`!-k` command-line switch. The choice of :func:`N_` here is totally arbitrary; it could have just as easily been :func:`MarkThisStringForTranslation`. Acknowledgements ---------------- The following people contributed code, feedback, design suggestions, previous implementations, and valuable experience to the creation of this module: * Peter Funk * James Henstridge * Juan David Ibáñez Palomar * Marc-André Lemburg * Martin von Löwis * François Pinard * Barry Warsaw * Gustavo Niemeyer .. rubric:: Footnotes .. [#] The default locale directory is system dependent; for example, on RedHat Linux it is :file:`/usr/share/locale`, but on Solaris it is :file:`/usr/lib/locale`. The :mod:`gettext` module does not try to support these system dependent defaults; instead its default is :file:`sys.prefix/share/locale`. For this reason, it is always best to call :func:`bindtextdomain` with an explicit absolute path at the start of your application. .. [#] See the footnote for :func:`bindtextdomain` above.
Save
cmd:
run