Skip to main content

A quick and easy internationalization library for Python.

Project description

quick-i18n

quick-i18n is a simple and efficient internationalization (i18n) library for Python applications. It allows you to manage translations using JSON files, supports dynamic language switching, and provides formatting for translation strings.

Features

  • Simple setup and integration
  • Supports multiple languages with dynamic switching
  • Uses JSON files for storing translations
  • Automatic handling of missing translations in development mode
  • Supports positional and keyword arguments for string formatting
  • Domain separation for organizing translations
  • Customizable translation directories

Installation

Install the package via pip:

pip install quick-i18n

Usage

from quicki18n import i18n

# Initialize the i18n class
t = i18n(
    languages=['en', 'es'],
    default_language='en',
    default_domain="default",
    dev_mode=True  # Set to False in production
)

# Set the current language
t.set_language('es')

# Get translations
print(t('Welcome to our application!'))  # Translates based on the current language

# Use formatting in translations
print(t('Greeting, {name}', name='Alice', domain='messages'))

After execution quick-i18n generate for You json files:

{
  "default": {
    "welcome-to-our-application": "Welcome to our application!"
  },
  "messages": {
    "greeting-name": "Greeting, {name}!"
  }
}

Development Mode

When dev_mode is set to True, missing translation keys are automatically added to all language files, making it easier to manage translations during development.

Recommendations for organizing file structure

When integrating the quick-i18n package into your Python project, it's important to organize your files and directories effectively to ensure maintainability and scalability. This guide provides recommendations for structuring your project to make the most out of quick-i18n.

Project Structure

A well-organized project structure enhances readability and maintainability. Here's a recommended structure when using quick-i18n:

your_project/
├── app/
   ├── __init__.py
   ├── i18n.py
   ├── main.py
   └── ... (other modules)
├── translations/
   ├── en.json
   ├── es.json
   ├── ru.json
   └── ... (other language files)
├── requirements.txt
├── README.md
└── ... (other files)
  • app/: Contains your application code.
  • translations/: Stores your translation JSON files.
  • requirements.txt: Lists your project dependencies.
  • README.md: Provides information about your project.

Translation Files

Place or generate your translation files in a dedicated translations/ directory at the root of your project. Each language has its own JSON file named after its language code (e.g., en.json for English).

Example en.json:

{
  "default": {
    "welcome": "Welcome to our application!",
    "farewell": "Goodbye, {name}!"
  },
  "errors": {
    "not_found": "The requested item was not found.",
    "unauthorized": "You are not authorized to perform this action."
  }
}

es.json

{
  "default": {
    "welcome": "¡Bienvenido a nuestra aplicación!",
    "farewell": "¡Adiós, {name}!"
  },
  "errors": {
    "not_found": "El elemento solicitado no fue encontrado.",
    "unauthorized": "No estás autorizado para realizar esta acción."
  }
}

Initializing quick-i18n

Initialize quick-i18n in a central location within your application, such as the init.py file of your app/ package or a dedicated module (e.g., app/i18n.py).

# app/i18n.py

import os
from quicki18n import i18n

# Determine the path to the translations directory
translations_path = os.path.join(os.path.dirname(__file__), '..', 'translations')

# Initialize the i18n instance
t = i18n(
    languages=['en', 'es', 'ru'],
    default_language='en',
    dev_mode=False,  # Set to True during development
    translations_path=translations_path
)
  • languages: List of supported language codes.
  • current_language: Default language for your application.
  • dev_mode: When True, missing translation keys are added automatically.
  • translations_path: Path to your translations/ directory.

Using Translations in Your Code

Import the translation instance t and use it to fetch translations within your application modules.

# app/main.py

from . import t

def greet_user(name):
    welcome_message = t('default.welcome')
    personalized_farewell = t('default.farewell', name=name)
    print(welcome_message)
    print(personalized_farewell)

if __name__ == "__main__":
    t.set_language('es')  # Set language to Spanish
    greet_user('Carlos')

Output:

¡Bienvenido a nuestra aplicación!
¡Adiós, Carlos!

Best Practices

  1. Consistent Key Naming: Use dot notation to organize translation keys into namespaces (e.g., default.welcome, errors.not_found). Keep key names consistent across all language files.
  2. Placeholder Usage: Use placeholders for dynamic content in your translations. Support both positional ({}) and keyword ({name}) placeholders. Ensure placeholders are consistent in all translations for a key.
  3. Language Codes: Use standard ISO 639-1 language codes (e.g., en for English, es for Spanish). This ensures compatibility and clarity.
  4. Development Mode: Enable dev_mode during development to automatically add missing keys. Remember to disable dev_mode in production to prevent unintended file modifications.
  5. Translation Updates: When adding new translations, update all language files to keep them in sync. Use empty strings or the original text as placeholders until translations are available.

License

This project is licensed under the MIT License - see the LICENSE file for details.

Contributing

Contributions are welcome! Please submit a pull request or open an issue for any improvements or bug fixes.

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

quick_i18n-0.1.2.tar.gz (6.3 kB view details)

Uploaded Source

Built Distribution

quick_i18n-0.1.2-py3-none-any.whl (6.3 kB view details)

Uploaded Python 3

File details

Details for the file quick_i18n-0.1.2.tar.gz.

File metadata

  • Download URL: quick_i18n-0.1.2.tar.gz
  • Upload date:
  • Size: 6.3 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/5.1.1 CPython/3.12.6

File hashes

Hashes for quick_i18n-0.1.2.tar.gz
Algorithm Hash digest
SHA256 006c13134c32172ad9f868a7f9dd16ab1613dab9f2b10438c095997084dbdacb
MD5 90c10f05f531bc687413e66805b5574e
BLAKE2b-256 fce874d5ffe5d759a95f6a7d90f7bc3164ebe1e966d55e84ee6ab9f2f807d033

See more details on using hashes here.

File details

Details for the file quick_i18n-0.1.2-py3-none-any.whl.

File metadata

  • Download URL: quick_i18n-0.1.2-py3-none-any.whl
  • Upload date:
  • Size: 6.3 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/5.1.1 CPython/3.12.6

File hashes

Hashes for quick_i18n-0.1.2-py3-none-any.whl
Algorithm Hash digest
SHA256 36d5633997db22239607dacea40fbbd2941ecf1ec6c7e9834cc4e2de9a74cf0d
MD5 135ce20c17a8d9951614110076038f3b
BLAKE2b-256 5e101a96b514a7b3501862ffe4b89f8e029770cbb9db491432da034b4f7052ee

See more details on using hashes here.

Supported by

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