Skip to main content

Lingopy is a lightweight localization library for Python that helps you manage localized messages effortlessly.

Project description

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 LocalizationError exception.
  • Flexible Usage: Supports string concatenation and repetition for localized messages.

Installation

You can include the Lingopy module in your project by simply copying the source code.

Usage

Basic Setup

First, define a language function that returns the current language code. Then, create an instance of 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 text property:
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:

  1. Set up your Flask application:

    from flask import Flask, request
    
    from src.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)
    
  2. Accessing Localized Messages: When a user accesses your application, the get_language function will determine the language based on the Accept-Language header sent by their browser. If the preferred language is not available, the Lingopy instance will fall back to the specified fallback language (in this case, Polish).

  3. 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.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

lingopy-0.1.0.tar.gz (5.9 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

lingopy-0.1.0-py3-none-any.whl (6.9 kB view details)

Uploaded Python 3

File details

Details for the file lingopy-0.1.0.tar.gz.

File metadata

  • Download URL: lingopy-0.1.0.tar.gz
  • Upload date:
  • Size: 5.9 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/5.1.1 CPython/3.12.4

File hashes

Hashes for lingopy-0.1.0.tar.gz
Algorithm Hash digest
SHA256 9b50723fb2a1564b89b06af8e697a95515d9219e11830cd01a9ec45c2b48872e
MD5 bf31c45487397bd404ed49b0d42384d0
BLAKE2b-256 890cacfc066f25ded404adf130d6c5520f9fb87cc4d4b3975fb74c3f00b30b8e

See more details on using hashes here.

File details

Details for the file lingopy-0.1.0-py3-none-any.whl.

File metadata

  • Download URL: lingopy-0.1.0-py3-none-any.whl
  • Upload date:
  • Size: 6.9 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/5.1.1 CPython/3.12.4

File hashes

Hashes for lingopy-0.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 1f4cd8f49de10c398dbe478112bc0283ba5691d753de208fdcfd94bce1a8391a
MD5 346fa0cc90a0bc5773334408ead5ad33
BLAKE2b-256 2dd77748b402a69c06654c0906ecd406653b04188c08f4caf42ddad527b5f042

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page