summaryrefslogtreecommitdiff
path: root/devdocs/python~3.12/library%2Fgettext.html
diff options
context:
space:
mode:
Diffstat (limited to 'devdocs/python~3.12/library%2Fgettext.html')
-rw-r--r--devdocs/python~3.12/library%2Fgettext.html169
1 files changed, 169 insertions, 0 deletions
diff --git a/devdocs/python~3.12/library%2Fgettext.html b/devdocs/python~3.12/library%2Fgettext.html
new file mode 100644
index 00000000..27fedf1c
--- /dev/null
+++ b/devdocs/python~3.12/library%2Fgettext.html
@@ -0,0 +1,169 @@
+ <span id="gettext-multilingual-internationalization-services"></span><h1>gettext — Multilingual internationalization services</h1> <p><strong>Source code:</strong> <a class="reference external" href="https://github.com/python/cpython/tree/3.12/Lib/gettext.py">Lib/gettext.py</a></p> <p>The <a class="reference internal" href="#module-gettext" title="gettext: Multilingual internationalization services."><code>gettext</code></a> module provides internationalization (I18N) and localization (L10N) services for your Python modules and applications. It supports both the GNU <strong class="program">gettext</strong> 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.</p> <p>Some hints on localizing your Python modules and applications are also given.</p> <section id="gnu-gettext-api"> <h2>GNU <strong class="program">gettext</strong> API</h2> <p>The <a class="reference internal" href="#module-gettext" title="gettext: Multilingual internationalization services."><code>gettext</code></a> module defines the following API, which is very similar to the GNU <strong class="program">gettext</strong> 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.</p> <dl class="py function"> <dt class="sig sig-object py" id="gettext.bindtextdomain">
+<code>gettext.bindtextdomain(domain, localedir=None)</code> </dt> <dd>
+<p>Bind the <em>domain</em> to the locale directory <em>localedir</em>. More concretely, <a class="reference internal" href="#module-gettext" title="gettext: Multilingual internationalization services."><code>gettext</code></a> will look for binary <code>.mo</code> files for the given domain using the path (on Unix): <code><em>localedir</em>/<em>language</em>/LC_MESSAGES/<em>domain</em>.mo</code>, where <em>language</em> is searched for in the environment variables <span class="target" id="index-0"></span><code>LANGUAGE</code>, <span class="target" id="index-1"></span><code>LC_ALL</code>, <span class="target" id="index-2"></span><code>LC_MESSAGES</code>, and <span class="target" id="index-3"></span><code>LANG</code> respectively.</p> <p>If <em>localedir</em> is omitted or <code>None</code>, then the current binding for <em>domain</em> is returned. <a class="footnote-reference brackets" href="#id3" id="id1">1</a></p> </dd>
+</dl> <dl class="py function"> <dt class="sig sig-object py" id="gettext.textdomain">
+<code>gettext.textdomain(domain=None)</code> </dt> <dd>
+<p>Change or query the current global domain. If <em>domain</em> is <code>None</code>, then the current global domain is returned, otherwise the global domain is set to <em>domain</em>, which is returned.</p> </dd>
+</dl> <span class="target" id="index-4"></span><dl class="py function"> <dt class="sig sig-object py" id="gettext.gettext">
+<code>gettext.gettext(message)</code> </dt> <dd>
+<p>Return the localized translation of <em>message</em>, based on the current global domain, language, and locale directory. This function is usually aliased as <code>_()</code> in the local namespace (see examples below).</p> </dd>
+</dl> <dl class="py function"> <dt class="sig sig-object py" id="gettext.dgettext">
+<code>gettext.dgettext(domain, message)</code> </dt> <dd>
+<p>Like <a class="reference internal" href="#gettext.gettext" title="gettext.gettext"><code>gettext()</code></a>, but look the message up in the specified <em>domain</em>.</p> </dd>
+</dl> <dl class="py function"> <dt class="sig sig-object py" id="gettext.ngettext">
+<code>gettext.ngettext(singular, plural, n)</code> </dt> <dd>
+<p>Like <a class="reference internal" href="#gettext.gettext" title="gettext.gettext"><code>gettext()</code></a>, but consider plural forms. If a translation is found, apply the plural formula to <em>n</em>, and return the resulting message (some languages have more than two plural forms). If no translation is found, return <em>singular</em> if <em>n</em> is 1; return <em>plural</em> otherwise.</p> <p>The Plural formula is taken from the catalog header. It is a C or Python expression that has a free variable <em>n</em>; the expression evaluates to the index of the plural in the catalog. See <a class="reference external" href="https://www.gnu.org/software/gettext/manual/gettext.html">the GNU gettext documentation</a> for the precise syntax to be used in <code>.po</code> files and the formulas for a variety of languages.</p> </dd>
+</dl> <dl class="py function"> <dt class="sig sig-object py" id="gettext.dngettext">
+<code>gettext.dngettext(domain, singular, plural, n)</code> </dt> <dd>
+<p>Like <a class="reference internal" href="#gettext.ngettext" title="gettext.ngettext"><code>ngettext()</code></a>, but look the message up in the specified <em>domain</em>.</p> </dd>
+</dl> <dl class="py function"> <dt class="sig sig-object py" id="gettext.pgettext">
+<code>gettext.pgettext(context, message)</code> </dt> <dd></dd>
+</dl> <dl class="py function"> <dt class="sig sig-object py" id="gettext.dpgettext">
+<code>gettext.dpgettext(domain, context, message)</code> </dt> <dd></dd>
+</dl> <dl class="py function"> <dt class="sig sig-object py" id="gettext.npgettext">
+<code>gettext.npgettext(context, singular, plural, n)</code> </dt> <dd></dd>
+</dl> <dl class="py function"> <dt class="sig sig-object py" id="gettext.dnpgettext">
+<code>gettext.dnpgettext(domain, context, singular, plural, n)</code> </dt> <dd>
+<p>Similar to the corresponding functions without the <code>p</code> in the prefix (that is, <a class="reference internal" href="#module-gettext" title="gettext: Multilingual internationalization services."><code>gettext()</code></a>, <a class="reference internal" href="#gettext.dgettext" title="gettext.dgettext"><code>dgettext()</code></a>, <a class="reference internal" href="#gettext.ngettext" title="gettext.ngettext"><code>ngettext()</code></a>, <a class="reference internal" href="#gettext.dngettext" title="gettext.dngettext"><code>dngettext()</code></a>), but the translation is restricted to the given message <em>context</em>.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.8.</span></p> </div> </dd>
+</dl> <p>Note that GNU <strong class="program">gettext</strong> also defines a <code>dcgettext()</code> method, but this was deemed not useful and so it is currently unimplemented.</p> <p>Here’s an example of typical usage for this API:</p> <pre data-language="python">import gettext
+gettext.bindtextdomain('myapplication', '/path/to/my/language/directory')
+gettext.textdomain('myapplication')
+_ = gettext.gettext
+# ...
+print(_('This is a translatable string.'))
+</pre> </section> <section id="class-based-api"> <h2>Class-based API</h2> <p>The class-based API of the <a class="reference internal" href="#module-gettext" title="gettext: Multilingual internationalization services."><code>gettext</code></a> module gives you more flexibility and greater convenience than the GNU <strong class="program">gettext</strong> API. It is the recommended way of localizing your Python applications and modules. <code>gettext</code> defines a <a class="reference internal" href="#gettext.GNUTranslations" title="gettext.GNUTranslations"><code>GNUTranslations</code></a> class which implements the parsing of GNU <code>.mo</code> format files, and has methods for returning strings. Instances of this class can also install themselves in the built-in namespace as the function <code>_()</code>.</p> <dl class="py function"> <dt class="sig sig-object py" id="gettext.find">
+<code>gettext.find(domain, localedir=None, languages=None, all=False)</code> </dt> <dd>
+<p>This function implements the standard <code>.mo</code> file search algorithm. It takes a <em>domain</em>, identical to what <a class="reference internal" href="#gettext.textdomain" title="gettext.textdomain"><code>textdomain()</code></a> takes. Optional <em>localedir</em> is as in <a class="reference internal" href="#gettext.bindtextdomain" title="gettext.bindtextdomain"><code>bindtextdomain()</code></a>. Optional <em>languages</em> is a list of strings, where each string is a language code.</p> <p>If <em>localedir</em> is not given, then the default system locale directory is used. <a class="footnote-reference brackets" href="#id4" id="id2">2</a> If <em>languages</em> is not given, then the following environment variables are searched: <span class="target" id="index-5"></span><code>LANGUAGE</code>, <span class="target" id="index-6"></span><code>LC_ALL</code>, <span class="target" id="index-7"></span><code>LC_MESSAGES</code>, and <span class="target" id="index-8"></span><code>LANG</code>. The first one returning a non-empty value is used for the <em>languages</em> 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.</p> <p><a class="reference internal" href="#gettext.find" title="gettext.find"><code>find()</code></a> then expands and normalizes the languages, and then iterates through them, searching for an existing file built of these components:</p> <p><code><em>localedir</em>/<em>language</em>/LC_MESSAGES/<em>domain</em>.mo</code></p> <p>The first such file name that exists is returned by <a class="reference internal" href="#gettext.find" title="gettext.find"><code>find()</code></a>. If no such file is found, then <code>None</code> is returned. If <em>all</em> 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.</p> </dd>
+</dl> <dl class="py function"> <dt class="sig sig-object py" id="gettext.translation">
+<code>gettext.translation(domain, localedir=None, languages=None, class_=None, fallback=False)</code> </dt> <dd>
+<p>Return a <code>*Translations</code> instance based on the <em>domain</em>, <em>localedir</em>, and <em>languages</em>, which are first passed to <a class="reference internal" href="#gettext.find" title="gettext.find"><code>find()</code></a> to get a list of the associated <code>.mo</code> file paths. Instances with identical <code>.mo</code> file names are cached. The actual class instantiated is <em>class_</em> if provided, otherwise <a class="reference internal" href="#gettext.GNUTranslations" title="gettext.GNUTranslations"><code>GNUTranslations</code></a>. The class’s constructor must take a single <a class="reference internal" href="../glossary#term-file-object"><span class="xref std std-term">file object</span></a> argument.</p> <p>If multiple files are found, later files are used as fallbacks for earlier ones. To allow setting the fallback, <a class="reference internal" href="copy#copy.copy" title="copy.copy"><code>copy.copy()</code></a> is used to clone each translation object from the cache; the actual instance data is still shared with the cache.</p> <p>If no <code>.mo</code> file is found, this function raises <a class="reference internal" href="exceptions#OSError" title="OSError"><code>OSError</code></a> if <em>fallback</em> is false (which is the default), and returns a <a class="reference internal" href="#gettext.NullTranslations" title="gettext.NullTranslations"><code>NullTranslations</code></a> instance if <em>fallback</em> is true.</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.3: </span><a class="reference internal" href="exceptions#IOError" title="IOError"><code>IOError</code></a> used to be raised, it is now an alias of <a class="reference internal" href="exceptions#OSError" title="OSError"><code>OSError</code></a>.</p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.11: </span><em>codeset</em> parameter is removed.</p> </div> </dd>
+</dl> <dl class="py function"> <dt class="sig sig-object py" id="gettext.install">
+<code>gettext.install(domain, localedir=None, *, names=None)</code> </dt> <dd>
+<p>This installs the function <code>_()</code> in Python’s builtins namespace, based on <em>domain</em> and <em>localedir</em> which are passed to the function <a class="reference internal" href="#gettext.translation" title="gettext.translation"><code>translation()</code></a>.</p> <p>For the <em>names</em> parameter, please see the description of the translation object’s <a class="reference internal" href="#gettext.NullTranslations.install" title="gettext.NullTranslations.install"><code>install()</code></a> method.</p> <p>As seen below, you usually mark the strings in your application that are candidates for translation, by wrapping them in a call to the <code>_()</code> function, like this:</p> <pre data-language="python">print(_('This string will be translated.'))
+</pre> <p>For convenience, you want the <code>_()</code> function to be installed in Python’s builtins namespace, so it is easily accessible in all modules of your application.</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.11: </span><em>names</em> is now a keyword-only parameter.</p> </div> </dd>
+</dl> <section id="the-nulltranslations-class"> <h3>The <a class="reference internal" href="#gettext.NullTranslations" title="gettext.NullTranslations"><code>NullTranslations</code></a> class</h3> <p>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 <a class="reference internal" href="#gettext.NullTranslations" title="gettext.NullTranslations"><code>NullTranslations</code></a>; this provides the basic interface you can use to write your own specialized translation classes. Here are the methods of <code>NullTranslations</code>:</p> <dl class="py class"> <dt class="sig sig-object py" id="gettext.NullTranslations">
+<code>class gettext.NullTranslations(fp=None)</code> </dt> <dd>
+<p>Takes an optional <a class="reference internal" href="../glossary#term-file-object"><span class="xref std std-term">file object</span></a> <em>fp</em>, which is ignored by the base class. Initializes “protected” instance variables <em>_info</em> and <em>_charset</em> which are set by derived classes, as well as <em>_fallback</em>, which is set through <a class="reference internal" href="#gettext.NullTranslations.add_fallback" title="gettext.NullTranslations.add_fallback"><code>add_fallback()</code></a>. It then calls <code>self._parse(fp)</code> if <em>fp</em> is not <code>None</code>.</p> <dl class="py method"> <dt class="sig sig-object py" id="gettext.NullTranslations._parse">
+<code>_parse(fp)</code> </dt> <dd>
+<p>No-op in the base class, this method takes file object <em>fp</em>, 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.</p> </dd>
+</dl> <dl class="py method"> <dt class="sig sig-object py" id="gettext.NullTranslations.add_fallback">
+<code>add_fallback(fallback)</code> </dt> <dd>
+<p>Add <em>fallback</em> 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.</p> </dd>
+</dl> <dl class="py method"> <dt class="sig sig-object py" id="gettext.NullTranslations.gettext">
+<code>gettext(message)</code> </dt> <dd>
+<p>If a fallback has been set, forward <code>gettext()</code> to the fallback. Otherwise, return <em>message</em>. Overridden in derived classes.</p> </dd>
+</dl> <dl class="py method"> <dt class="sig sig-object py" id="gettext.NullTranslations.ngettext">
+<code>ngettext(singular, plural, n)</code> </dt> <dd>
+<p>If a fallback has been set, forward <code>ngettext()</code> to the fallback. Otherwise, return <em>singular</em> if <em>n</em> is 1; return <em>plural</em> otherwise. Overridden in derived classes.</p> </dd>
+</dl> <dl class="py method"> <dt class="sig sig-object py" id="gettext.NullTranslations.pgettext">
+<code>pgettext(context, message)</code> </dt> <dd>
+<p>If a fallback has been set, forward <a class="reference internal" href="#gettext.pgettext" title="gettext.pgettext"><code>pgettext()</code></a> to the fallback. Otherwise, return the translated message. Overridden in derived classes.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.8.</span></p> </div> </dd>
+</dl> <dl class="py method"> <dt class="sig sig-object py" id="gettext.NullTranslations.npgettext">
+<code>npgettext(context, singular, plural, n)</code> </dt> <dd>
+<p>If a fallback has been set, forward <a class="reference internal" href="#gettext.npgettext" title="gettext.npgettext"><code>npgettext()</code></a> to the fallback. Otherwise, return the translated message. Overridden in derived classes.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.8.</span></p> </div> </dd>
+</dl> <dl class="py method"> <dt class="sig sig-object py" id="gettext.NullTranslations.info">
+<code>info()</code> </dt> <dd>
+<p>Return a dictionary containing the metadata found in the message catalog file.</p> </dd>
+</dl> <dl class="py method"> <dt class="sig sig-object py" id="gettext.NullTranslations.charset">
+<code>charset()</code> </dt> <dd>
+<p>Return the encoding of the message catalog file.</p> </dd>
+</dl> <dl class="py method"> <dt class="sig sig-object py" id="gettext.NullTranslations.install">
+<code>install(names=None)</code> </dt> <dd>
+<p>This method installs <a class="reference internal" href="#gettext.NullTranslations.gettext" title="gettext.NullTranslations.gettext"><code>gettext()</code></a> into the built-in namespace, binding it to <code>_</code>.</p> <p>If the <em>names</em> parameter is given, it must be a sequence containing the names of functions you want to install in the builtins namespace in addition to <code>_()</code>. Supported names are <code>'gettext'</code>, <code>'ngettext'</code>, <code>'pgettext'</code>, and <code>'npgettext'</code>.</p> <p>Note that this is only one way, albeit the most convenient way, to make the <code>_()</code> function available to your application. Because it affects the entire application globally, and specifically the built-in namespace, localized modules should never install <code>_()</code>. Instead, they should use this code to make <code>_()</code> available to their module:</p> <pre data-language="python">import gettext
+t = gettext.translation('mymodule', ...)
+_ = t.gettext
+</pre> <p>This puts <code>_()</code> only in the module’s global namespace and so only affects calls within this module.</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.8: </span>Added <code>'pgettext'</code> and <code>'npgettext'</code>.</p> </div> </dd>
+</dl> </dd>
+</dl> </section> <section id="the-gnutranslations-class"> <h3>The <a class="reference internal" href="#gettext.GNUTranslations" title="gettext.GNUTranslations"><code>GNUTranslations</code></a> class</h3> <p>The <code>gettext</code> module provides one additional class derived from <a class="reference internal" href="#gettext.NullTranslations" title="gettext.NullTranslations"><code>NullTranslations</code></a>: <a class="reference internal" href="#gettext.GNUTranslations" title="gettext.GNUTranslations"><code>GNUTranslations</code></a>. This class overrides <code>_parse()</code> to enable reading GNU <strong class="program">gettext</strong> format <code>.mo</code> files in both big-endian and little-endian format.</p> <p><a class="reference internal" href="#gettext.GNUTranslations" title="gettext.GNUTranslations"><code>GNUTranslations</code></a> parses optional metadata out of the translation catalog. It is convention with GNU <strong class="program">gettext</strong> to include metadata as the translation for the empty string. This metadata is in <span class="target" id="index-9"></span><a class="rfc reference external" href="https://datatracker.ietf.org/doc/html/rfc822.html"><strong>RFC 822</strong></a>-style <code>key: value</code> pairs, and should contain the <code>Project-Id-Version</code> key. If the key <code>Content-Type</code> is found, then the <code>charset</code> property is used to initialize the “protected” <code>_charset</code> instance variable, defaulting to <code>None</code> 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 is assumed.</p> <p>Since message ids are read as Unicode strings too, all <code>*gettext()</code> methods will assume message ids as Unicode strings, not byte strings.</p> <p>The entire set of key/value pairs are placed into a dictionary and set as the “protected” <code>_info</code> instance variable.</p> <p>If the <code>.mo</code> file’s magic number is invalid, the major version number is unexpected, or if other problems occur while reading the file, instantiating a <a class="reference internal" href="#gettext.GNUTranslations" title="gettext.GNUTranslations"><code>GNUTranslations</code></a> class can raise <a class="reference internal" href="exceptions#OSError" title="OSError"><code>OSError</code></a>.</p> <dl class="py class"> <dt class="sig sig-object py" id="gettext.GNUTranslations">
+<code>class gettext.GNUTranslations</code> </dt> <dd>
+<p>The following methods are overridden from the base class implementation:</p> <dl class="py method"> <dt class="sig sig-object py" id="gettext.GNUTranslations.gettext">
+<code>gettext(message)</code> </dt> <dd>
+<p>Look up the <em>message</em> id in the catalog and return the corresponding message string, as a Unicode string. If there is no entry in the catalog for the <em>message</em> id, and a fallback has been set, the look up is forwarded to the fallback’s <a class="reference internal" href="#gettext.NullTranslations.gettext" title="gettext.NullTranslations.gettext"><code>gettext()</code></a> method. Otherwise, the <em>message</em> id is returned.</p> </dd>
+</dl> <dl class="py method"> <dt class="sig sig-object py" id="gettext.GNUTranslations.ngettext">
+<code>ngettext(singular, plural, n)</code> </dt> <dd>
+<p>Do a plural-forms lookup of a message id. <em>singular</em> is used as the message id for purposes of lookup in the catalog, while <em>n</em> is used to determine which plural form to use. The returned message string is a Unicode string.</p> <p>If the message id is not found in the catalog, and a fallback is specified, the request is forwarded to the fallback’s <a class="reference internal" href="#gettext.NullTranslations.ngettext" title="gettext.NullTranslations.ngettext"><code>ngettext()</code></a> method. Otherwise, when <em>n</em> is 1 <em>singular</em> is returned, and <em>plural</em> is returned in all other cases.</p> <p>Here is an example:</p> <pre data-language="python">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}
+</pre> </dd>
+</dl> <dl class="py method"> <dt class="sig sig-object py" id="gettext.GNUTranslations.pgettext">
+<code>pgettext(context, message)</code> </dt> <dd>
+<p>Look up the <em>context</em> and <em>message</em> id in the catalog and return the corresponding message string, as a Unicode string. If there is no entry in the catalog for the <em>message</em> id and <em>context</em>, and a fallback has been set, the look up is forwarded to the fallback’s <a class="reference internal" href="#gettext.pgettext" title="gettext.pgettext"><code>pgettext()</code></a> method. Otherwise, the <em>message</em> id is returned.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.8.</span></p> </div> </dd>
+</dl> <dl class="py method"> <dt class="sig sig-object py" id="gettext.GNUTranslations.npgettext">
+<code>npgettext(context, singular, plural, n)</code> </dt> <dd>
+<p>Do a plural-forms lookup of a message id. <em>singular</em> is used as the message id for purposes of lookup in the catalog, while <em>n</em> is used to determine which plural form to use.</p> <p>If the message id for <em>context</em> is not found in the catalog, and a fallback is specified, the request is forwarded to the fallback’s <a class="reference internal" href="#gettext.npgettext" title="gettext.npgettext"><code>npgettext()</code></a> method. Otherwise, when <em>n</em> is 1 <em>singular</em> is returned, and <em>plural</em> is returned in all other cases.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.8.</span></p> </div> </dd>
+</dl> </dd>
+</dl> </section> <section id="solaris-message-catalog-support"> <h3>Solaris message catalog support</h3> <p>The Solaris operating system defines its own binary <code>.mo</code> file format, but since no documentation can be found on this format, it is not supported at this time.</p> </section> <section id="the-catalog-constructor"> <h3>The Catalog constructor</h3> <p id="index-10">GNOME uses a version of the <a class="reference internal" href="#module-gettext" title="gettext: Multilingual internationalization services."><code>gettext</code></a> module by James Henstridge, but this version has a slightly different API. Its documented usage was:</p> <pre data-language="python">import gettext
+cat = gettext.Catalog(domain, localedir)
+_ = cat.gettext
+print(_('hello world'))
+</pre> <p>For compatibility with this older module, the function <code>Catalog()</code> is an alias for the <a class="reference internal" href="#gettext.translation" title="gettext.translation"><code>translation()</code></a> function described above.</p> <p>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.</p> </section> </section> <section id="internationalizing-your-programs-and-modules"> <span id="i18n-howto"></span><h2>Internationalizing your programs and modules</h2> <p>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:</p> <ol class="arabic simple"> <li>prepare your program or module by specially marking translatable strings</li> <li>run a suite of tools over your marked files to generate raw messages catalogs</li> <li>create language-specific translations of the message catalogs</li> <li>use the <a class="reference internal" href="#module-gettext" title="gettext: Multilingual internationalization services."><code>gettext</code></a> module so that message strings are properly translated</li> </ol> <p>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 <code>_('...')</code> — that is, a call to the function <a class="reference internal" href="#module-gettext" title="gettext: Multilingual internationalization services."><code>_</code></a>. For example:</p> <pre data-language="python">filename = 'mylog.txt'
+message = _('writing a log message')
+with open(filename, 'w') as fp:
+ fp.write(message)
+</pre> <p>In this example, the string <code>'writing a log message'</code> is marked as a candidate for translation, while the strings <code>'mylog.txt'</code> and <code>'w'</code> are not.</p> <p>There are a few tools to extract the strings meant for translation. The original GNU <strong class="program">gettext</strong> only supported C or C++ source code but its extended version <strong class="program">xgettext</strong> scans code written in a number of languages, including Python, to find strings marked as translatable. <a class="reference external" href="https://babel.pocoo.org/">Babel</a> is a Python internationalization library that includes a <code>pybabel</code> script to extract and compile message catalogs. François Pinard’s program called <strong class="program">xpot</strong> does a similar job and is available as part of his <a class="reference external" href="https://github.com/pinard/po-utils">po-utils package</a>.</p> <p>(Python also includes pure-Python versions of these programs, called <strong class="program">pygettext.py</strong> and <strong class="program">msgfmt.py</strong>; some Python distributions will install them for you. <strong class="program">pygettext.py</strong> is similar to <strong class="program">xgettext</strong>, but only understands Python source code and cannot handle other programming languages such as C or C++. <strong class="program">pygettext.py</strong> supports a command-line interface similar to <strong class="program">xgettext</strong>; for details on its use, run <code>pygettext.py
+--help</code>. <strong class="program">msgfmt.py</strong> is binary compatible with GNU <strong class="program">msgfmt</strong>. With these two programs, you may not need the GNU <strong class="program">gettext</strong> package to internationalize your Python applications.)</p> <p><strong class="program">xgettext</strong>, <strong class="program">pygettext</strong>, and similar tools generate <code>.po</code> 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.</p> <p>Copies of these <code>.po</code> 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 <code>&lt;language-name&gt;.po</code> file that’s compiled into a machine-readable <code>.mo</code> binary catalog file using the <strong class="program">msgfmt</strong> program. The <code>.mo</code> files are used by the <a class="reference internal" href="#module-gettext" title="gettext: Multilingual internationalization services."><code>gettext</code></a> module for the actual translation processing at run-time.</p> <p>How you use the <a class="reference internal" href="#module-gettext" title="gettext: Multilingual internationalization services."><code>gettext</code></a> 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.</p> <section id="localizing-your-module"> <h3>Localizing your module</h3> <p>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 <strong class="program">gettext</strong> API but instead the class-based API.</p> <p>Let’s say your module is called “spam” and the module’s various natural language translation <code>.mo</code> files reside in <code>/usr/share/locale</code> in GNU <strong class="program">gettext</strong> format. Here’s what you would put at the top of your module:</p> <pre data-language="python">import gettext
+t = gettext.translation('spam', '/usr/share/locale')
+_ = t.gettext
+</pre> </section> <section id="localizing-your-application"> <h3>Localizing your application</h3> <p>If you are localizing your application, you can install the <code>_()</code> 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 <code>_('...')</code> without having to explicitly install it in each file.</p> <p>In the simple case then, you need only add the following bit of code to the main driver file of your application:</p> <pre data-language="python">import gettext
+gettext.install('myapplication')
+</pre> <p>If you need to set the locale directory, you can pass it into the <a class="reference internal" href="#gettext.install" title="gettext.install"><code>install()</code></a> function:</p> <pre data-language="python">import gettext
+gettext.install('myapplication', '/usr/share/locale')
+</pre> </section> <section id="changing-languages-on-the-fly"> <h3>Changing languages on the fly</h3> <p>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:</p> <pre data-language="python">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()
+</pre> </section> <section id="deferred-translations"> <h3>Deferred translations</h3> <p>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:</p> <pre data-language="python">animals = ['mollusk',
+ 'albatross',
+ 'rat',
+ 'penguin',
+ 'python', ]
+# ...
+for a in animals:
+ print(a)
+</pre> <p>Here, you want to mark the strings in the <code>animals</code> list as being translatable, but you don’t actually want to translate them until they are printed.</p> <p>Here is one way you can handle this situation:</p> <pre data-language="python">def _(message): return message
+
+animals = [_('mollusk'),
+ _('albatross'),
+ _('rat'),
+ _('penguin'),
+ _('python'), ]
+
+del _
+
+# ...
+for a in animals:
+ print(_(a))
+</pre> <p>This works because the dummy definition of <code>_()</code> simply returns the string unchanged. And this dummy definition will temporarily override any definition of <code>_()</code> in the built-in namespace (until the <a class="reference internal" href="../reference/simple_stmts#del"><code>del</code></a> command). Take care, though if you have a previous definition of <code>_()</code> in the local namespace.</p> <p>Note that the second use of <code>_()</code> will not identify “a” as being translatable to the <strong class="program">gettext</strong> program, because the parameter is not a string literal.</p> <p>Another way to handle this is with the following example:</p> <pre data-language="python">def N_(message): return message
+
+animals = [N_('mollusk'),
+ N_('albatross'),
+ N_('rat'),
+ N_('penguin'),
+ N_('python'), ]
+
+# ...
+for a in animals:
+ print(_(a))
+</pre> <p>In this case, you are marking translatable strings with the function <code>N_()</code>, which won’t conflict with any definition of <code>_()</code>. However, you will need to teach your message extraction program to look for translatable strings marked with <code>N_()</code>. <strong class="program">xgettext</strong>, <strong class="program">pygettext</strong>, <code>pybabel extract</code>, and <strong class="program">xpot</strong> all support this through the use of the <code>-k</code> command-line switch. The choice of <code>N_()</code> here is totally arbitrary; it could have just as easily been <code>MarkThisStringForTranslation()</code>.</p> </section> </section> <section id="acknowledgements"> <h2>Acknowledgements</h2> <p>The following people contributed code, feedback, design suggestions, previous implementations, and valuable experience to the creation of this module:</p> <ul class="simple"> <li>Peter Funk</li> <li>James Henstridge</li> <li>Juan David Ibáñez Palomar</li> <li>Marc-André Lemburg</li> <li>Martin von Löwis</li> <li>François Pinard</li> <li>Barry Warsaw</li> <li>Gustavo Niemeyer</li> </ul> <h4 class="rubric">Footnotes</h4> <dl class="footnote brackets"> <dt class="label" id="id3">
+<code>1</code> </dt> <dd>
+<p>The default locale directory is system dependent; for example, on Red Hat Linux it is <code>/usr/share/locale</code>, but on Solaris it is <code>/usr/lib/locale</code>. The <code>gettext</code> module does not try to support these system dependent defaults; instead its default is <code><em>sys.base_prefix</em>/share/locale</code> (see <a class="reference internal" href="sys#sys.base_prefix" title="sys.base_prefix"><code>sys.base_prefix</code></a>). For this reason, it is always best to call <a class="reference internal" href="#gettext.bindtextdomain" title="gettext.bindtextdomain"><code>bindtextdomain()</code></a> with an explicit absolute path at the start of your application.</p> </dd> <dt class="label" id="id4">
+<code>2</code> </dt> <dd>
+<p>See the footnote for <a class="reference internal" href="#gettext.bindtextdomain" title="gettext.bindtextdomain"><code>bindtextdomain()</code></a> above.</p> </dd> </dl> </section> <div class="_attribution">
+ <p class="_attribution-p">
+ &copy; 2001&ndash;2023 Python Software Foundation<br>Licensed under the PSF License.<br>
+ <a href="https://docs.python.org/3.12/library/gettext.html" class="_attribution-link">https://docs.python.org/3.12/library/gettext.html</a>
+ </p>
+</div>