Internationalization
Locale contexts, messages, named formats, and strict localized-input parsers.
make_context function
make_context(app: Citry, locale: str | None = None, time_zone: str | None = None) -> LocaleContextCreate a locale context for one Citry application.
The application argument keeps the owning engine explicit while hiding the extension-registry lookup needed to reach its i18n extension. The returned context does not change application, task, or process state.
Example
from citry.ext.i18n import make_context context = make_context(app, locale=request.locale) html = Page().render(provides={"citry_i18n": context})
Parameters
appCitry- The Citry application that owns the i18n configuration.localestr | None- A configured or inferred source locale, orNoneto use the configured or inferred default locale.time_zonestr | None- An IANA time-zone name, orNonefor a zone-free context.
Returns
LocaleContext: A validated immutable locale context for that application.
Raises
I18nNotConfiguredError- The application has neither i18n settings nor registered component messages.ValueError- A locale or time-zone value is invalid or unavailable.
I18nExtension class
Bases: Extension
Own one application's catalog graph, profiles, and locale contexts.
Registered component messages activate the server catalog in source mode. Explicit engine settings additionally activate selectable locales, catalog packages, named profiles, parsing, and browser delivery.
Application code normally obtains this built-in extension from app.extensions.get_extension("i18n"). Create a context with make_context(), pass it through root render(provides={"citry_i18n": context}), and use for_context() outside components. Components receive the same operations through self.i18n.
configured attribute
configured: boolReturn whether the engine supplied the required i18n settings.
available attribute
available: boolReturn whether settings or registered component messages provide server i18n.
config attribute
config: I18nEngineConfigReturn the validated immutable engine configuration.
catalog_revision attribute
catalog_revision: strThe current checked catalog graph revision.
context attribute
context: LocaleContextBuild a fresh context for the configured or inferred source locale.
context_for_component function
context_for_component(component: Component) -> LocaleContextReturn the exact context provided to a component, or the default.
format_for_component function
format_for_component(component: Component, usage: I18nUsageCollector | None = None) -> I18nFormatter parse_for_component function
parse_for_component(component: Component, usage: I18nUsageCollector | None = None) -> I18nParser for_context function
for_context(context: LocaleContext) -> I18nServiceReturn the complete i18n service bound to one explicit context.
Parameters
contextLocaleContext- The locale, direction, time zone, and catalog revisions that every operation must use.
Returns
I18nService: Translation, resolution, formatting, and parsing operations that
Raises
I18nNotConfiguredError- The engine has no i18n configuration.TypeError-contextis not an exactLocaleContext.
on_extension_created function
on_extension_created(ctx: OnExtensionCreatedContext) -> None on_messages_loaded function
on_messages_loaded(ctx: OnMessagesLoadedContext) -> str | None on_component_registered function
on_component_registered(ctx: OnComponentRegisteredContext) -> None on_component_unregistered function
on_component_unregistered(ctx: OnComponentUnregisteredContext) -> None inspect_template_namespace function
inspect_template_namespace(ctx: TemplateNamespaceContext) -> TemplateNamespaceContribution | None on_template_compiled function
on_template_compiled(ctx: OnTemplateCompiledContext) -> list[Any]Install render-time wrappers for direct, dynamic, and spread $c-tr.
on_component_rendered function
on_component_rendered(ctx: OnComponentRenderedContext) -> NoneSeal checked binding metadata after the complete component body rendered.
on_render_context_merge function
on_render_context_merge(ctx: OnRenderContextMergeContext) -> None on_dependencies function
on_dependencies(ctx: OnDependenciesContext) -> NoneEmit browser i18n only for a client-enabled provider subtree.
stage_render_cache function
stage_render_cache(ctx: OnRenderCacheStageContext) -> StagedRenderCacheContributionValidate cached i18n metadata and bind it to fresh render IDs.
make_context function
make_context(locale: str | None = None, time_zone: str | None = None) -> LocaleContextBuild one validated locale context without changing shared state.
Parameters
localestr | None- An allowed configured/source locale, orNonefor the configured or inferred default locale.time_zonestr | None- An IANA time-zone name, orNonefor a zone-free context.
Returns
LocaleContext: A new immutable context carrying the current catalog and profile revisions.
Raises
I18nNotConfiguredError- The extension has neither settings nor registered component message sources.ValueError- The locale or time zone is invalid or unavailable.
browser_artifact function
browser_artifact(locale: str, outputs: tuple[MessageOutputUse, ...] | tuple[str, ...], messages: tuple[str, ...]) -> dict[str, object]Compile one exact browser catalog partition from checked roots.
browser_parser_artifact function
Build locale-specific records for the checked browser parsers.
tr function
tr(message_id: str, attr: str | None = None, context: LocaleContext | None = None, **values: object = {}) -> strResolve one message or attribute to plain text.
Prefer for_context(context).tr(...) outside components so the locale dependency stays explicit. Omitting context here uses a new default context and is mainly useful for tooling and simple startup checks.
resolve function
resolve(message_id: str, attr: str | None = None, context: LocaleContext | None = None, **values: object = {}) -> LocalizedTextResolve one message and retain its selected locale and fallback data.
message_id and attr must name a public checked output. values must match that output's @param interface exactly. The supplied context must still carry the current catalog revision.
resolve_rich function
resolve_rich(message_id: str, values: Mapping[str, object], slots: Mapping[str, object], attr: str | None = None, context: LocaleContext | None = None) -> dict[str, object]Resolve one rich message to escaped text records and named Slot parts.
This is the lower-level operation used by <c-trans>. Application code should normally use that component so fills retain their Citry scope and ownership.
I18n class
Bases: ExtensionConfig
Per-component i18n settings and access to the provided locale context.
Set Component.I18n.messages_locale to the locale in which that component's messages / messages_file source is authored. Declaring a message asset activates server translations even when the engine has no i18n settings. Declare client_messages only for finite dynamic message IDs that static browser analysis cannot see. Instances expose the nearest explicit context, translation, formatting, and parsing through self.i18n.
configured attribute
configured: boolReturn whether this component's engine has explicit i18n settings.
available attribute
available: boolReturn whether server translation is available from settings or component messages.
context attribute
context: LocaleContextReturn the explicit locale context provided to this component tree.
resolve function
resolve(message_id: str, attr: str | None = None, **values: object = {}) -> LocalizedTextResolve text and keep the selected locale and fallback metadata.
format attribute
format: I18nFormatterReturn named formatter operations bound to this component context.
parse attribute
parse: I18nParserReturn strict parser operations bound to this component context.
I18nService class
Use messages, formatting, and parsing with one explicit locale context.
Create this service with I18nExtension.for_context. Components receive the same operations through Component.i18n.
Attributes
contextLocaleContext- The exact locale context used by every operation.formatI18nFormatter- Named formatting operations bound tocontext.parseI18nParser- Strict parsing operations bound tocontext.
available attribute
available: boolReturn whether settings or component messages provide server i18n.
context attribute
context: LocaleContextReturn the exact locale context bound to this service.
resolve function
resolve(message_id: str, attr: str | None = None, **values: object = {}) -> LocalizedTextResolve text and retain its selected locale and fallback metadata.
format attribute
format: I18nFormatterReturn the named formatter operations bound to this context.
parse attribute
parse: I18nParserReturn the strict parser operations bound to this context.
I18nFormatter class
Format canonical values with one component or locale context.
Citry creates this object for I18n.format and I18nService.format. Application code should use those entry points rather than constructing it directly.
relative_time function
Format an exact relative value with a named relative-time profile.
I18nParser class
Parse localized edits with one component or locale context.
Citry creates this object for I18n.parse and I18nService.parse. Application code should use those entry points rather than constructing it directly.
number function
number(input: str, format: str) -> NumberParseResultParse one strict localized number edit into an exact decimal.
percent function
percent(input: str, format: str) -> PercentParseResultParse one strict localized percent edit into its exact ratio.
date function
date(input: str, format: str) -> DateParseResultParse one strict localized date string with a text-input profile.
date_segments function
date_segments(input: DateSegments, format: str) -> DateParseResultParse named date fields with a segmented-input profile.
time function
time(input: str, format: str) -> TimeParseResultParse one strict localized wall-clock time string.
time_segments function
time_segments(input: TimeSegments, format: str) -> TimeParseResultParse named wall-clock fields with a segmented-input profile.
datetime function
datetime(input: str, format: str, fold: str | None = None) -> DateTimeParseResultParse local datetime text and resolve it through the context time zone.
datetime_segments function
datetime_segments(input: DateTimeSegments, format: str, fold: str | None = None) -> DateTimeParseResultParse named local datetime fields and resolve an explicit DST fold.
LocaleContext class
All explicit render inputs that can change localized output.
Attributes
localestr- The selected canonical locale.fallback_localestuple[str, ...]- The ordered configured fallback chain.directionLiteral['ltr', 'rtl']- The writing direction used by the render subtree.time_zonestr | None- The explicit IANA time zone, orNonefor zone-free work.tzdb_revisionstr- The exact time-zone data revision.catalog_revisionstr- The exact checked message graph revision.formats_revisionstr- The exact named-profile registry revision.
identity attribute
Plain immutable data that identifies every input to localized output.
LocalizedText class
Resolved text plus the locale metadata needed by semantic wrappers.
Attributes
textstr- The formatted message text.localestr- The locale that supplied the selected pattern.directionLiteral['ltr', 'rtl']- The selected pattern's writing direction.used_fallbackbool- Whether resolution used a locale other than the request.
FormatRegistry class
Store the application's named formatter profiles.
The profile names are application-defined. Each value uses one of Citry's checked profile types so the Rust server and browser can share the same contract.
Example
Give call sites names that describe why they format a value::
formats = FormatRegistry( number={ "measurement": NumberFormat(), }, date={ "invoice-date": DateFormat( length="long", ), }, ) # Inside a component: text = self.i18n.format.number( meters, format="measurement", )
Attributes
numberMapping[str, NumberFormat]- Exact-decimal number profiles.percentMapping[str, PercentFormat]- Ratio-based percent profiles and their input rules.currencyMapping[str, CurrencyFormat]- Currency profiles.dateMapping[str, DateFormat]- Calendar-date profiles.timeMapping[str, TimeFormat]- Wall-clock time profiles.datetimeMapping[str, DateTimeFormat]- Instant and time-zone profiles.relative_timeMapping[str, RelativeTimeFormat]- Relative-time profiles.listMapping[str, ListFormat]- Conjunction and disjunction list profiles.unitMapping[str, UnitFormat]- Standalone measurement-unit profiles.
NumberParseResult class
One strict localized number edit without losing unfinished text.
Attributes
inputstr- The exact user edit.stateLiteral['valid', 'incomplete', 'invalid']-valid,incomplete, orinvalid.valueDecimal | None- The canonical exact decimal when valid.errorstr | None- A stable explanation for an invalid result, otherwiseNone.
valid attribute
valid: boolReturn whether the edit contains one complete canonical number.
PercentFormat class
Format a canonical ratio and optionally accept localized percent edits.
A value of Decimal("0.125") represents 12.5 percent. Parsing returns the same ratio domain value.
Attributes
inputPercentInput- The strict editing rule used byi18n.parse.percent().
PercentInput class
Choose whether a percent edit includes the locale's percent affix.
Attributes
affixLiteral['required', 'omit']-"required"accepts the same affix that formatting emits."omit"accepts only the localized number, which is useful when a control renders the affix outside its editable field.
PercentParseResult class
Keep one localized percent edit and its canonical ratio separate.
Attributes
inputstr- The exact user edit.stateLiteral['valid', 'incomplete', 'invalid']-valid,incomplete, orinvalid.valueDecimal | None- The canonical ratio when valid;0.125means 12.5 percent.errorstr | None- A stable explanation for an invalid result, otherwiseNone.
DateFormat class
DateInput class
Declare how a named date profile accepts editable input.
Attributes
modeLiteral['strict_text', 'segments']-"strict_text"accepts one localized date string."segments"accepts named year, month, and day edit segments.two_digit_year_startint | None- The first year in the selected calendar's explicit 100-year window.Nonerequires a full year.
DateSegments class
DateParseResult class
Keep one localized date edit and its canonical Python date separate.
ambiguous reports an input that needs an explicit calendar decision. valid is the only state with a canonical value.
TimeFormat class
TimeInput class
Declare how a named wall-clock time profile accepts editable input.
strict_text accepts one locale-shaped string. segments accepts a TimeSegments value from a segmented control.
TimeSegments class
Hold editable fields from a segmented wall-clock time control.
second and day_period are optional because the named profile decides whether those fields are present.
TimeParseResult class
Keep one localized time edit and its canonical wall-clock value separate.
The result is a zone-free datetime.time. Converting it to an instant requires a date and time zone.
valid attribute
valid: boolReturn whether the edit contains one complete wall-clock time.
DateTimeFormat class
Format an instant after conversion to the context's explicit IANA zone.
Attributes
lengthLiteral['short', 'medium', 'long']- The locale-sensitive date and time display length.time_zone_nameLiteral['none', 'short', 'long']- Whether and how to display the resolved zone name.inputDateTimeInput | None- The strict local-edit rule.Nonekeeps the profile display-only.
DateTimeInput class
DateTimeSegments class
Combine named date and time fields from one local datetime control.
DateTimeParseResult class
Keep a local datetime edit separate from its resolved aware instant.
An ambiguous daylight-saving fold returns both aware instants in alternatives. Pass fold="earlier" or fold="later" to the parser to resolve that choice explicitly.
valid attribute
valid: boolReturn whether the edit resolved to one complete aware instant.
ListFormat class
Format a conjunction or disjunction list.
kind chooses βandβ or βorβ. length chooses the locale's wide, short, or narrow pattern.
UnitFormat class
Format an exact value with an explicit CLDR unit identifier.
Attributes
widthLiteral['long', 'short', 'narrow']- How fully ICU4X writes the unit name.
I18nNotConfiguredError class
Bases: I18nError
Raised when an i18n operation needs settings or messages that are absent.
I18nRuntimeUnavailableError class
Bases: I18nError
Raised when the requested i18n operation cannot run in the current context.