Lingopy
Lingopy is a lightweight localization library for Python that helps you manage localized messages effortlessly.
Features
- Dynamic Language Selection: Choose the current language dynamically using a callable function.
- Fallback Language: Define a fallback language for cases where the current language localization is not available.
- Custom Exceptions: Handle localization errors gracefully with a custom
LocalizationErrorexception. - Flexible Usage: Supports string concatenation and repetition for localized messages.
Installation
To install Lingopy, you can use the following command in your terminal:
pip install lingopy
Usage
Basic Setup
First, define a language function that returns the current language code. Then, create an instance of Lingopy:
from lingopy import Lingopy
lang_func = lambda: "en"
lingopy = Lingopy(lang_func=lang_func, fallback_lang="pl")
Localizing Messages
You can create localized messages by passing key-value pairs to the localized method:
BAD_EMAIL_MSG = lingopy.localized(
en="You have entered the bad e-mail.",
pl="Wpisałeś zły adres e-mail.",
)
BAD_PASSWORD_MSG = lingopy.localized(
en="You have entered the bad password.",
pl="Wpisałeś złe hasło."
)
You can also localize messages without accessing the Lingopy (Lingopy is the configuration base for the localized strings).
from lingopy import Localized
BAD_EMAIL_MSG = Localized(
lang_func=lambda: 'en',
fallback_lang='pl',
en="You have entered the bad e-mail.",
pl="Wpisałeś zły adres e-mail.",
)
BAD_PASSWORD_MSG = Localized(
lang_func=lambda: 'en',
fallback_lang='pl',
en="You have entered the bad password.",
pl="Wpisałeś złe hasło."
)
Accessing Localized Messages
You can retrieve the localized text using:
- The
textproperty:
print(BAD_EMAIL_MSG.text) # Outputs the message in the current language
print(BAD_PASSWORD_MSG.text) # Outputs the message in the current language
- By calling it:
print(BAD_EMAIL_MSG()) # Outputs the message in the current language
print(BAD_PASSWORD_MSG()) # Outputs the message in the current language
- By applying
str()or__str__()to it:
print(str(BAD_EMAIL_MSG)) # Outputs the message in the current language
print(BAD_PASSWORD_MSG.__str__()) # Outputs the message in the current language
- Sometimes just using the variable will work.
print(BAD_EMAIL_MSG) # Outputs the message in the current language. Works because `print` automatically uses __str__ on printed values.
print(BAD_PASSWORD_MSG) # Outputs the message in the current language. Works because `print` automatically uses __str__ on printed values.
String Operations
Localized messages can be concatenated or repeated:
print(BAD_EMAIL_MSG + BAD_PASSWORD_MSG) # Concatenates the localized messages
print(BAD_EMAIL_MSG + " Added text") # Concatenates localized message with string
print(BAD_EMAIL_MSG.text + " Added text") # Concatenates localized message with string
print(BAD_EMAIL_MSG * 2) # Repeats the localized message
# Will raise error:
print("Added text" + BAD_EMAIL_MSG) # String class does not handle adding other type than `str` to it.
Advanced example with lang_func.
The lang_func in Lingopy is a callable that returns the current language code. This design allows for dynamic language selection based on the context of your application, making it especially useful in web applications.
Example: Using lang_func with Flask.
In a Flask application, you might want to determine the user's preferred language based on HTTP request headers. For instance, you can read the Accept-Language header, which is commonly used by browsers to indicate the user's language preferences.
Here's how you can set it up:
-
Set up your Flask application:
from flask import Flask, request from lingopy import Lingopy app = Flask(__name__) # Define the language function def get_language(): # Get the 'Accept-Language' header from the request lang = request.headers.get('Accept-Language') # Return None when header is not presented. if not lang: return None # Split the header values into a list languages = lang.split(',') # Remove duplicates while maintaining order unique_languages = [] for language in languages: # Simplify the language code (e.g., 'pl-PL' => 'pl') simplified_language = language.split('-')[0] # Add to the list only if it's not already included if simplified_language not in unique_languages: unique_languages.append(simplified_language) # Return the first result or default to 'en' return unique_languages[0] if unique_languages else None # Create an instance of Lingopy lingopy = Lingopy(lang_func=get_language, fallback_lang="pl") @app.route('/') def home(): # Localized messages welcome_msg = lingopy.localized( en="Welcome to the application!", pl="Witamy w aplikacji!" ) return welcome_msg.text # Returns the message in the user's language if __name__ == "__main__": app.run(debug=True)
-
Accessing Localized Messages: When a user accesses your application, the
get_languagefunction will determine the language based on theAccept-Languageheader sent by their browser. If the preferred language is not available, theLingopyinstance will fall back to the specified fallback language (in this case, Polish). -
Handling Edge Cases: If the user's browser does not specify a preferred language, or if the specified language is not supported, the application will gracefully return the message in the fallback language.
This approach allows you to create a more user-friendly application that respects the user's language preferences, making your application accessible to a broader audience.
Conclusion
Lingopy makes it easy to manage localized messages in your applications, providing flexibility and clarity. For more advanced usage, you can explore modifying the lang_func and defining additional localizations as needed.
License
This project is licensed under the MIT License.
Metadata
Release files for lingopy 0.1.0.1
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 | Actions |
|---|---|---|---|---|
| lingopy-0.1.0.1.tar.gz | 5.9 kB | Without provenance | Details for lingopy-0.1.0.1.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| lingopy-0.1.0.1-py3-none-any.whl | Python 3 | none | any | Details for lingopy-0.1.0.1-py3-none-any.whl |
Total release size: 12.9 kB
Release files / lingopy-0.1.0.1.tar.gz
| Download URL | lingopy-0.1.0.1.tar.gz |
|---|---|
| Size | 5.9 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
363f666af2f6e97e40ce5e7d54b0f5ed38b45848b8de41dc38fc3a35d9dd26b6
|
|
BLAKE2b-256 checksum How to use checksums |
2dcd80727598ec044996611f413656ccf931db24573a93eac544dfddceeb061f
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/5.1.1 CPython/3.12.4
|
Release files / lingopy-0.1.0.1-py3-none-any.whl
| Download URL | lingopy-0.1.0.1-py3-none-any.whl |
|---|---|
| Size | 7.0 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
e82d19b5da4c2bb05da0d608ded1ae73b3cb0e3ee820fd8af4c2108e628c3917
|
|
BLAKE2b-256 checksum How to use checksums |
8b629c16abca78dea193b3173dc4f135207bf490c0f5cda620aca6240f050608
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/5.1.1 CPython/3.12.4
|
Security for lingopy 0.1.0.1
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.
To learn more about protecting yourself from malicious actors, visit our package security documentation.