Fluent Syntax Parser
Fluent.syntax is the Python implementation for parsing, analyzing, processing, and serializing Fluent Translation List (FTL) files. It provides tools for working with the Abstract Syntax Tree (AST) of Fluent messages. As part of the broader Project Fluent, it helps unleash the expressive power of natural language in localization. The library is currently at version 0.19.0 and receives updates as part of the `python-fluent` project, with releases tied to Fluent specification updates and Python ecosystem changes.
Warnings
- breaking Version 0.19.0 dropped official support for Python 2.7 and 3.5. Users on these Python versions should remain on `fluent-syntax<0.19.0`.
- breaking In version 0.18.0, the deprecated `BaseNode.traverse` method was removed. Additionally, `Visitor` and `Transformer` classes were refactored and moved from `fluent.syntax.ast` to `fluent.syntax.visitor`.
- gotcha Prior to version 0.18.1, serializing multiline patterns (especially those starting with special Fluent syntax characters like `[`, `.`, `*`, or `{`) could lead to incorrect output or syntax errors if the pattern elements didn't explicitly force a new line. `FluentSerializer` now correctly handles these cases.
- gotcha While `fluent.syntax.visitor.Transformer` allows in-place modification of an AST, care must be taken. Arbitrary modifications can lead to an AST that, when serialized, does not produce valid Fluent content. Always validate the transformed AST if performing complex manipulations.
Install
-
pip install fluent-syntax
Imports
- FluentParser
from fluent.syntax.parser import FluentParser
- FluentSerializer
from fluent.syntax.serializer import FluentSerializer
- ast
from fluent.syntax import ast
- Visitor
from fluent.syntax.visitor import Visitor
- Transformer
from fluent.syntax.visitor import Transformer
Quickstart
from fluent.syntax.parser import FluentParser
from fluent.syntax.serializer import FluentSerializer
ftl_source = """
# Welcome message
hello = Hello, { $username }!
# Plural example
num-emails = { $num ->
[one] You have one email.
*[other] You have { $num } emails.
}
"""
parser = FluentParser()
resource = parser.parse(ftl_source)
print("--- Parsed AST ---")
# For a more readable AST, you might want to use a custom visitor or ast.dump
# For simplicity, we'll just print the resource object's representation.
print(resource)
serializer = FluentSerializer()
serialized_ftl = serializer.serialize(resource)
print("\n--- Serialized FTL ---")
print(serialized_ftl)