DocsPython
Python SDK reference
The generic-translation Python package - messages, hashing, locales, API clients, runtime, Flask, FastAPI and Django integrations, the generic-translation-py extractor and known differences from JavaScript.
On this page
The generic-translation package (repository generic-translation/generic-translation-python) is a Python port of @generic-translation/core and @generic-translation/node. It is typed (py.typed), needs Python 3.9+, and has one required dependency, Babel.
Not on PyPI yet. Install from the repository: pip install "git+https://github.com/generic-translation/generic-translation-python", or with an extra, pip install "generic-translation[flask] @ git+https://github.com/generic-translation/generic-translation-python". After publication pip install generic-translation will work, with extras flask, fastapi, django and async (the last adds httpx).
Messages
Every message is an ICU MessageFormat string with numbered or named tags.
from generic_translation import format_message, validate_message, extract_variables, extract_tags, messages_compatible
format_message("{count, plural, =0 {No files} one {# file} other {# files}}", {"count": 1200}, "de")
format_message("Total: {total, number, ::currency/EUR}", {"total": 9.5}, "fr")
format_message("Read the <0>docs</0>", {"0": lambda chunk: f"[{chunk}]"}) # callable per tag
validate_message("Hi {name") # {"valid": False, "error": "..."}
messages_compatible("Hi <0>{name}</0>", "Salut {name}") # {"ok": False, "problems": ["Missing tag <0>"]}
Also exported: parse_message, escape_message, render_message and MessageSyntaxError. Values may be str, int, float, Decimal, bool (rendered true/false, like JS), None (renders nothing) and datetime/date (a medium date). A missing value renders its placeholder. data_format="STRING" returns the text untouched. MessageSyntaxError.position is a UTF-16 offset identical to the JS core; .index is the Python string index.
Hashing
from generic_translation import hash_source
hash_source("Hello, world!") # "b1395fddbbacadda17814498697c69f1"
hash_source("Save", context="button label")
hash_source("raw text", data_format="STRING")
The first 32 hex characters of SHA-256 over JSON.stringify([dataFormat, source, context ?? ""]), serialized exactly as JavaScript does. id is not part of the hash. See Hashing.
Locales
standardize_locale, is_valid_locale, determine_locale, parse_accept_language, get_locale_direction, get_locale_name, is_same_language, get_locale_properties, get_locale_emoji, requires_translation and SUPPORTED_LOCALES. Formatting helpers: format_num, format_currency, format_date_time, format_relative_time, format_list.
standardize_locale("en_us") # "en-US"
determine_locale(["fr-CA", "en"], ["en", "fr"]) # "fr"
get_locale_direction("ar") # "rtl"
API clients
from generic_translation import GenericTranslation, AsyncGenericTranslation, GenericTranslationApiError
client = GenericTranslation(project_id="prj_...", api_key="gt-api-...") # defaults: GENERIC_TRANSLATION_PROJECT_ID, GENERIC_TRANSLATION_API_KEY, GENERIC_TRANSLATION_API_URL
client.translate("Hello {name}", "es", context="greeting")
client.translate_many([{"source": "Save"}, {"source": "Cancel"}], "ja") # chunked 50 per request
sub = client.submit_entries([{"source": "Hello"}], locales=["es", "fr"], branch="main")
job = client.wait_for_job(sub["jobId"], timeout=600, on_progress=print) # returns on completed and failed
client.get_translations("es")
client.publish(["es"])
client.fetch_cdn("es") # sends no credentials
client.upload_file("guide.md", "md", "# Hi")
client.list_files(); client.download_file(file_id, "es"); client.get_project(); client.get_job(job_id)
Results are plain dicts with the API’s JSON keys. Errors raise GenericTranslationApiError with .status and .code (network failures are 0 / network_error, timeouts 0 / timeout). AsyncGenericTranslation has the same methods as coroutines and works as async with. Without a project_id, requests go to /v1/projects/current/..., resolved from the key; fetch_cdn needs a real id. See the REST API.
Runtime
initialize_generic_translation(
default_locale="en",
locales=["es", "ja"],
project_id=None,
api_key=None, # CDN source / runtime translation (env defaults)
translations_dir=None, # <dir>/<locale>.json
load_translations=None, # callable(locale) -> {hash: text}; highest priority, may be async
cache_ttl=60.0, # seconds; float("inf") never refreshes
runtime_translation=False, # False | True/"background" | "await"
dictionary=None, # dict or path to a nested dictionary JSON
)
Sources are tried in order and the first usable one wins per locale: your loader, translations_dir, then the CDN (no credentials). A source that raises or has nothing falls through.
Caching. The first request loads a locale (concurrent first requests share one load). Within the TTL there is no I/O. After it, the stale map is served at once while one background thread refreshes it; a failed refresh keeps the stale map. Thread-safe. preload_translations(), clear_translation_cache(locale) and get_translations(locale) are available.
Locale binding uses contextvars, so it is correct per thread and per asyncio task:
from generic_translation import with_locale, get_locale, t
with with_locale("es-MX"): # matched against your configured locales
get_locale() # "es"
t("Hello")
t() call shape. t(message, /, _context=None, _id=None, **values). Context is part of the hash, _id is not. Tags with numeric names are passed as **{"0": callable}.
msg() declares messages at module scope; they carry context and id and are collected for submission:
from generic_translation import msg, t, get_messages, get_client
WELCOME = msg("Welcome back, {name}!", context="page header", id="home.welcome")
t(WELCOME, name="Ada")
get_client().submit_entries([m.to_entry() for m in get_messages()])
d() reads a dictionary of keyed strings (leaves are "message" or ["message", {"context": "..."}], ids are dot paths). Unknown ids return the id.
Runtime translation asks the API for strings with no translation yet. It needs a project_id and a key with translations:generate. "background" returns the source immediately and fills in the translation from a worker thread; "await" makes t() block until it arrives. Failures fall back to the source and are not retried for 60 seconds. tx(text, locale=..., context=...) (and await atx(...)) translate arbitrary text such as user content, as opaque STRING data. get_t(locale) returns a translator bound to one locale.
Runtime translation is synchronous in Python (a worker thread or a blocking call), unlike @generic-translation/node, where it is awaited.
Framework integrations
All three negotiate ?locale=, then the generic-translation-locale cookie, then Accept-Language, then the default; bind the locale for the request; and send Content-Language and Vary: Accept-Language.
Flask
pip install "generic-translation[flask] @ git+https://github.com/generic-translation/generic-translation-python"
from generic_translation.flask import GenericTranslation # alias: GenericTranslationFlask
GenericTranslation(app, locale_selector=lambda: current_user_locale(), set_cookie=True) # options are optional
Inside requests, g.locale and g.t("...") are available. Jinja globals: t, d, locale() and locale_dir(). Output is HTML-escaped by Jinja. Note that genericTranslation.Generic Translation (the API client) and generic_translation.flask.Generic Translation (the extension) are different classes.
FastAPI / Starlette
from fastapi import Depends, FastAPI
from generic_translation.fastapi import GenericTranslationMiddleware, get_t, get_request_locale
app = FastAPI()
app.add_middleware(GenericTranslationMiddleware) # pure ASGI; loads translations off the event loop
@app.get("/")
def home(tt=Depends(get_t), locale=Depends(get_request_locale)):
return {"text": tt("Hello {name}", name="Ada")}
Django
# settings.py
INSTALLED_APPS = [..., "generic_translation.django"]
MIDDLEWARE = [..., "generic_translation.django.middleware.GenericTranslationMiddleware"] # sync and async
# optional: GENERIC_TRANSLATION_QUERY_PARAM, GENERIC_TRANSLATION_COOKIE_NAME, GENERIC_TRANSLATION_CONTENT_LANGUAGE, GENERIC_TRANSLATION_LOCALE_SELECTOR
{% load generic_translation %}
<html lang="{% current_locale %}" dir="{% locale_direction %}">
{% t "Hello {name}" name=user.first_name %}
{% t "Save" _context="button label" as save_label %}
{% d "nav.home" %}
request.locale and request.t are set too. Tag output goes through Django’s autoescaping.
The generic-translation-py command
The console script is generic-translation-py (or python -m generic_translation), named to avoid clashing with the JavaScript CLI’s generic-translation binary.
generic-translation-py extract [--json] [--write] [--src GLOB ...] [--ignore-errors]
generic-translation-py translate [--locales es,ja] [--branch main] [--force] [--publish] [--timeout 600] [--dry-run]
What it finds. Python via ast: t("literal", ...), msg("literal", context=, id=) and literal _context= / _id=, honoring import aliases (from generic_translation import t as _, import generic_translation as gt), translators bound with get_t() / Depends(get_t) / Translator annotations, and g.t(...) / request.t(...). Constant concatenation is folded. In templates (.html .jinja .jinja2 .j2 .txt): {{ t("...") }}, {% set x = t("...") %} and {% t "..." %}. The dictionary file from the config is included.
What it rejects. Everything is validated as ICU. Non-literal first arguments (t(variable), f-strings, t()) and non-literal _context= are reported as file:line:column error non_literal; invalid ICU as invalid_icu. Errors exit 1 unless --ignore-errors. Python is scanned statically, so calls through arbitrary aliases of a translator, beyond the spellings above, are not seen.
translate submits entries in chunks of 2000, polls the job, downloads the translations and writes the output files in the JS CLI’s format (sorted keys, two-space JSON, trailing newline, only hashes found in your code). Unlike the JS CLI it keeps no lock file (the server de-duplicates by hash) and does not process the files config; use the JS CLI or GenericTranslation.upload_file for whole files. src globs from a JS-oriented config that name no Python or template files fall back to the defaults (**/*.py, **/templates/**/*.{html,jinja,jinja2,j2,txt}).
Differences from JavaScript
Hashes were compared against fixtures generated from the built JS core: 260 of 260 identical, as are parser error text and positions, messages_compatible, escape_message and the locale helpers. Formatting was compared on 1,149 cases across en, es, fr, de, ja, ar, ru and pl: 1,132 byte-identical, 1,143 identical once non-breaking and thin spaces are normalized. The package documents these known differences:
| Difference | Cause |
|---|---|
| Numeric dates are epoch seconds, not milliseconds. Strings are parsed as ISO-8601 or RFC 2822; values without a zone are UTC (JS uses the process zone). | Python’s time.time() convention. |
Whitespace: Babel emits a narrow no-break space before AM/PM in English times and before г. in Russian dates; Node prints a plain space. |
Babel follows CLDR; V8 patches it back. |
Spanish selectordinal: Babel gives es an ordinal one category, Node’s ICU reports only other (differs for 1, 3, 13, 21, 23, 101). Other locales also differ in a scan: af and bg ordinals, vi cardinals, gl for 1,000,000. |
Newer CLDR data in Babel. |
{d, time, long} UTC zone name: ICU prints UTC everywhere; Babel localizes it (the library special-cases UTC long). |
Babel. |
Skeleton coverage: engineering, scientific, narrow currency symbols and measure-unit/... follow Babel and may differ. Date skeletons use CLDR available-formats. |
Babel, not ICU’s skeleton engine. |
Number grouping: minimum grouping digits (for example no separator for 1234 in es, pl, pt-PT) comes from a small table derived from Node. |
Missing in Babel. |
| Compact notation: ICU’s rounding is reproduced on top of Babel’s patterns; unusual locales are untested. | Babel. |
Date and time strings can therefore differ in small ways from a JavaScript run of the same message. Hashes never do.
Something wrong or unclear on this page? Open an issue.