Fluent Runtime

0.4.0 · active · verified Sat Apr 11

Fluent Runtime is the Python implementation of Project Fluent's runtime component, providing localization capabilities for expressive translations. It handles parsing and formatting of Fluent Localization (FTL) files. The current version is 0.4.0, with new releases occurring infrequently, often in conjunction with updates to the `fluent.syntax` library.

Warnings

Install

Imports

Quickstart

Initializes `FluentResource` objects from FTL strings, then creates `FluentBundle` objects for specific locales. `FluentLocalization` acts as the high-level manager, providing an easy way to switch locales and format messages using `format_value`.

from fluent.runtime import FluentResource, FluentBundle, FluentLocalization
from datetime import datetime

# 1. Define your FTL resources
resource_en = FluentResource("""
hello = Hello, { $name }!
welcome = Welcome, today is {DATETIME($date)}
""")

resource_fr = FluentResource("""
hello = Bonjour, { $name }!
welcome = Bienvenue, aujourd'hui c'est le {DATETIME($date)}
""")

# 2. Create FluentBundles for each locale
bundle_en = FluentBundle(["en-US"], use_isolating=False)
bundle_en.add_resource(resource_en)

bundle_fr = FluentBundle(["fr"], use_isolating=False)
bundle_fr.add_resource(resource_fr)

# 3. Use FluentLocalization as the main entrypoint
loc = FluentLocalization(
    ["en-US", "fr"], 
    [
        lambda locales: bundle_en, # Provider function for 'en-US'
        lambda locales: bundle_fr  # Provider function for 'fr'
    ]
)

# 4. Format messages
message_en_hello, errors_en = loc.format_value("hello", {"name": "World"})
print(f"EN Hello: {message_en_hello}")

message_fr_welcome, errors_fr = loc.format_value("welcome", {"date": datetime.now()})
print(f"FR Welcome: {message_fr_welcome}")

# Example Output:
# EN Hello: Hello, World!
# FR Welcome: Bienvenue, aujourd'hui c'est le 2024-04-11 12:34:56

view raw JSON →