Minimal string translation library for Python
In summary:
- Developers reference translatable strings using identifiers in an enumeration class.
- Language-specific strings are written in several enumeration classes.
- The library transparently transforms string identifiers into already translated strings, depending on the system locale or user-selected locale.
This is neither a full internationalization library nor suitable for usual translation workflows. Make sure it meets your needs. If not, there are other libraries that do the job, for example, gettext.
How to use
Translate text for each locale
Define all translatable strings in an enumeration class. Those enumerations are called translators in the context of this library. Additionally:
- You must also define a
_langattribute and set its value to the corresponding locale or language string. A list of valid locale strings can be found at saimana.com. - You should also define a
_domainattribute and set its value to your application's name or any other random string. This prevents any conflict with translators from other libraries (if any). If not given, current module name is used, so you must create all your translators in the same module in that case.
For example:
from enum import Enum
class EN(Enum):
_lang = "en"
_domain = "appstrings.example"
TEST = "Hello world!"
class ES_MX(Enum):
_lang = "es_MX"
_domain = "appstrings.example"
TEST = "¡Hola mundo!"
Then, all translators must be "installed" at initialization:
from appstrings import install
install(EN)
install(ES_MX)
The library will check that all installed translators enumerate the same set of constants, except for "sunder" and "dunder" ones. Use that notation for non-translatable attributes if you need to. For example:
class ES_MX(Enum):
_lang = "es_MX"
_domain = "appstrings.example"
_note = "this is a developer note, not to be translated"
TEST = "¡Hola mundo!"
Note that another library imported in your project may use appstrings as well, thus installing its own translators. Use the _domain attribute to prevent any conflict.
Use already translated text
The function gettext() is used for translation. For example:
from appstrings import gettext
print(gettext(EN.TEST))
You may want to alias gettext to _ for convenience:
_ = gettext
print(_(EN.TEST)) # Print translated string, depending on current locale
This way, you may disable translation at any time for development purposes:
# _ = gettext
_ = lambda id: id._value_
print(_(EN.TEST)) # Always print all strings in english, for now
The library chooses the best-matching translator for the current translation locale, which is initialized from _locale._getdefaultlocale().
You may force a specific locale for translation at any time:
from appstrings import set_translation_locale
set_translation_locale("es_MX")
print(_(EN.TEST)) # Prints text in Spanish language of Mexico
then force the system locale again:
set_translation_locale()
Note that forcing a specific locale not available in your application will not magically translate your strings to that locale.
Fallback to a default language
In the previous examples, there is no translator for the locale pt_BR, to say one.
In such a case, the translator used in gettext() will work as the default language for non-translated locales.
In the early example, Brazilian people would read the text in english.
However, if print(_(ES_MX.TEST)) were used instead, Brazilian people would read the text in Spanish.
The ability to change the default language at any time comes from aliases:
STR = EN
print(_(STR.TEST)) # Prints TEST string in english if there is no matching translator
STR = ES_MX
print(_(STR.TEST)) # Prints TEST string in Spanish if there is no matching translator
This approach is developer-friendly, but not user-friendly.
Be user-friendly
Your application should allow the user to choose an available language via command-line parameters, environment variables or other means.
The function get_installed_translators() will help in order to show a list of
available languages:
print("Available languages/locales:")
for translator in get_installed_translators(STR._domain._value_):
print(translator._lang._value_)
Obviously, you already know which languages are available in your application, but this approach ensures you don't have to modify your code after adding a new translator.
Call set_translation_locale() to make effective the user preference.
Organize your code for translation
You may spread your translators along many source files as long as your application imports and installs them.
For example:
flowchart TB
main["__main__.py (your application)"]
default["translation.py (defines default language)"]
lang_es["translation_es.py (defines Spanish translator)"]
lang_pt["translation_pt.py (defines Portuguese translator)"]
main --imports--> default
default --imports--> lang_es
default --imports--> lang_pt
But the following schema will work just the same:
flowchart TB
main["__main__.py (your application)"]
default["translation.py (defines default language)"]
lang_es["translation_es.py (defines Spanish translator)"]
lang_pt["translation_pt.py (defines Portuguese translator)"]
main --imports--> default
main --imports--> lang_es
main --imports--> lang_pt
The "translation*.py" files would look like this:
from enum import Enum
from appstrings import install
class CertainTranslator(Enum):
_lang = ...
_domain = ...
TEXT1 = ...
TEXT2 = ...
...
install(CertainTranslator)
That is all about this library. As simple as that.
Troubleshooting
-
Why some strings are properly translated, but not others?
Ensure all your translators have a _domain attribute set to the very same value (case-sensitive).
-
I get a TranslatorException : String ID XXX from YYYY is missing at ZZZZ. Why ?
There are two possible reasons:
- One of your translators is missing a string that others have. Check.
- Your application is in conflict with some library. User another string in the "_domain" attribute.
Metadata
Release files for appstrings 1.0.2
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | |
|---|---|---|---|---|
| appstrings-1.0.2.tar.gz | 21.3 kB | Without provenance | Details |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Reset |
|---|---|---|---|---|
| appstrings-1.0.2-py3-none-any.whl | Python 3 | none | any | Details |
Total release size: 37.0 kB
Release files / appstrings-1.0.2.tar.gz
| Download URL | appstrings-1.0.2.tar.gz |
|---|---|
| Size | 21.3 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
f9dc3dd2d1f0246ec35e431fdfc7aa820a0d21009f267edf4fee28373ac30fb3
|
|
BLAKE2b-256 checksum How to use checksums |
645f506fcf9cf67372ccf7cbb01908db44144a8314779c807b7e491b772a04c9
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/5.1.0 CPython/3.11.7
|
Release files / appstrings-1.0.2-py3-none-any.whl
| Download URL | appstrings-1.0.2-py3-none-any.whl |
|---|---|
| Size | 15.7 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
912633328b797f325b4028ee4579246588a078d48a84eec4dd29a80ff8bb52fe
|
|
BLAKE2b-256 checksum How to use checksums |
4ec135910abdd12fe5084acc3ade9aaa3559df687d61b1339ea436b11e2d6d81
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/5.1.0 CPython/3.11.7
|
Security for appstrings 1.0.2
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
No provenance found
None of the files in this release were uploaded with provenance metadata.
A note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.