Theme
Version
GitHub PyPI Discord
On this page

Internationalization

Locale contexts, messages, named formats, and strict localized-input parsers.

View source

make_context function

make_context(app: Citry, locale: str | None = None, time_zone: str | None = None) -> LocaleContext

Create 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

  • app Citry - The Citry application that owns the i18n configuration.
  • locale str | None - A configured or inferred source locale, or None to use the configured or inferred default locale.
  • time_zone str | None - An IANA time-zone name, or None for 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.
View source

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.

View source

configured attribute

configured: bool

Return whether the engine supplied the required i18n settings.

View source

available attribute

available: bool

Return whether settings or registered component messages provide server i18n.

View source

config attribute

config: I18nEngineConfig

Return the validated immutable engine configuration.

View source

catalog_revision attribute

catalog_revision: str

The current checked catalog graph revision.

View source

urls attribute

urls: list[URLRoute]

Serve the browser runtime and exact message-partition endpoint.

View source

context attribute

context: LocaleContext

Build a fresh context for the configured or inferred source locale.

View source

context_for_component function

context_for_component(component: Component) -> LocaleContext

Return the exact context provided to a component, or the default.

View source

format_for_component function

format_for_component(component: Component, usage: I18nUsageCollector | None = None) -> I18nFormatter
View source

parse_for_component function

parse_for_component(component: Component, usage: I18nUsageCollector | None = None) -> I18nParser
View source

for_context function

for_context(context: LocaleContext) -> I18nService

Return the complete i18n service bound to one explicit context.

Parameters

  • context LocaleContext - 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 - context is not an exact LocaleContext.
View source

validate_config_fields function

validate_config_fields(fields: Mapping[str, Any], component: type[Component] | None = None) -> None
View source

on_template_compiled function

on_template_compiled(ctx: OnTemplateCompiledContext) -> list[Any]

Install render-time wrappers for direct, dynamic, and spread $c-tr.

View source

on_component_rendered function

on_component_rendered(ctx: OnComponentRenderedContext) -> None

Seal checked binding metadata after the complete component body rendered.

View source

on_dependencies function

on_dependencies(ctx: OnDependenciesContext) -> None

Emit browser i18n only for a client-enabled provider subtree.

View source

export_render_cache function

export_render_cache(ctx: OnRenderCacheExportContext) -> dict[str, object]

Detach i18n metadata for the selected cached subtree.

View source

stage_render_cache function

stage_render_cache(ctx: OnRenderCacheStageContext) -> StagedRenderCacheContribution

Validate cached i18n metadata and bind it to fresh render IDs.

View source

make_context function

make_context(locale: str | None = None, time_zone: str | None = None) -> LocaleContext

Build one validated locale context without changing shared state.

Parameters

  • locale str | None - An allowed configured/source locale, or None for the configured or inferred default locale.
  • time_zone str | None - An IANA time-zone name, or None for 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.
View source

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.

View source

browser_parser_artifact function

browser_parser_artifact(locale: str) -> dict[str, object]

Build locale-specific records for the checked browser parsers.

View source

tr function

tr(message_id: str, attr: str | None = None, context: LocaleContext | None = None, **values: object = {}) -> str

Resolve 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.

View source

resolve function

resolve(message_id: str, attr: str | None = None, context: LocaleContext | None = None, **values: object = {}) -> LocalizedText

Resolve 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.

View source

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.

View source

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.

View source

configured attribute

configured: bool

Return whether this component's engine has explicit i18n settings.

View source

available attribute

available: bool

Return whether server translation is available from settings or component messages.

View source

context attribute

context: LocaleContext

Return the explicit locale context provided to this component tree.

View source

tr function

tr(message_id: str, attr: str | None = None, **values: object = {}) -> str

Resolve one message or attribute to plain text.

View source

resolve function

resolve(message_id: str, attr: str | None = None, **values: object = {}) -> LocalizedText

Resolve text and keep the selected locale and fallback metadata.

View source

format attribute

Return named formatter operations bound to this component context.

View source

parse attribute

parse: I18nParser

Return strict parser operations bound to this component context.

View source

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

  • context LocaleContext - The exact locale context used by every operation.
  • format I18nFormatter - Named formatting operations bound to context.
  • parse I18nParser - Strict parsing operations bound to context.
View source

configured attribute

configured: bool

Return whether the owning engine configured i18n.

View source

available attribute

available: bool

Return whether settings or component messages provide server i18n.

View source

context attribute

context: LocaleContext

Return the exact locale context bound to this service.

View source

tr function

tr(message_id: str, attr: str | None = None, **values: object = {}) -> str

Resolve one message to plain text with the bound context.

View source

resolve function

resolve(message_id: str, attr: str | None = None, **values: object = {}) -> LocalizedText

Resolve text and retain its selected locale and fallback metadata.

View source

format attribute

Return the named formatter operations bound to this context.

View source

parse attribute

parse: I18nParser

Return the strict parser operations bound to this context.

View source

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.

View source

number function

number(value: int | Decimal, format: str) -> str

Format an exact integer or decimal with a named number profile.

View source

percent function

percent(value: int | Decimal, format: str) -> str

Format an exact ratio with a named percent profile.

View source

currency function

currency(value: int | Decimal, currency: str, format: str) -> str

Format an exact value and ISO 4217 code with a currency profile.

View source

date function

date(value: date, format: str) -> str

Format a calendar date with a named date profile.

View source

time function

time(value: time, format: str) -> str

Format a zone-free wall-clock time with a named profile.

View source

datetime function

datetime(value: datetime, format: str) -> str

Format an aware instant in the context's explicit time zone.

View source

relative_time function

relative_time(value: int | Decimal, unit: str, format: str) -> str

Format an exact relative value with a named relative-time profile.

View source

list function

list(values: object, format: str) -> str

Format non-empty strings as a localized conjunction or disjunction.

View source

unit function

unit(value: int | Decimal, unit: str, format: str) -> str

Format an exact value with an explicit CLDR unit identifier.

View source

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.

View source

number function

number(input: str, format: str) -> NumberParseResult

Parse one strict localized number edit into an exact decimal.

View source

percent function

percent(input: str, format: str) -> PercentParseResult

Parse one strict localized percent edit into its exact ratio.

View source

date function

date(input: str, format: str) -> DateParseResult

Parse one strict localized date string with a text-input profile.

View source

date_segments function

date_segments(input: DateSegments, format: str) -> DateParseResult

Parse named date fields with a segmented-input profile.

View source

time function

time(input: str, format: str) -> TimeParseResult

Parse one strict localized wall-clock time string.

View source

time_segments function

time_segments(input: TimeSegments, format: str) -> TimeParseResult

Parse named wall-clock fields with a segmented-input profile.

View source

datetime function

datetime(input: str, format: str, fold: str | None = None) -> DateTimeParseResult

Parse local datetime text and resolve it through the context time zone.

View source

datetime_segments function

datetime_segments(input: DateTimeSegments, format: str, fold: str | None = None) -> DateTimeParseResult

Parse named local datetime fields and resolve an explicit DST fold.

View source

LocaleContext class

All explicit render inputs that can change localized output.

Attributes

  • locale str - The selected canonical locale.
  • fallback_locales tuple[str, ...] - The ordered configured fallback chain.
  • direction Literal['ltr', 'rtl'] - The writing direction used by the render subtree.
  • time_zone str | None - The explicit IANA time zone, or None for zone-free work.
  • tzdb_revision str - The exact time-zone data revision.
  • catalog_revision str - The exact checked message graph revision.
  • formats_revision str - The exact named-profile registry revision.
View source

LocalizedText class

Resolved text plus the locale metadata needed by semantic wrappers.

Attributes

  • text str - The formatted message text.
  • locale str - The locale that supplied the selected pattern.
  • direction Literal['ltr', 'rtl'] - The selected pattern's writing direction.
  • used_fallback bool - Whether resolution used a locale other than the request.
View source

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

View source

NumberFormat class

Use ICU4X's locale-default exact-decimal format and input grammar.

View source

NumberInput class

Declare the strict notation accepted by a named number profile.

View source

notation attribute

notation: Literal['decimal', 'decimal_or_scientific']
View source

NumberParseResult class

One strict localized number edit without losing unfinished text.

Attributes

  • input str - The exact user edit.
  • state Literal['valid', 'incomplete', 'invalid'] - valid, incomplete, or invalid.
  • value Decimal | None - The canonical exact decimal when valid.
  • error str | None - A stable explanation for an invalid result, otherwise None.
View source

state attribute

state: Literal['valid', 'incomplete', 'invalid']
View source

valid attribute

valid: bool

Return whether the edit contains one complete canonical number.

View source

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

  • input PercentInput - The strict editing rule used by i18n.parse.percent().
View source

PercentInput class

Choose whether a percent edit includes the locale's percent affix.

Attributes

  • affix Literal['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.
View source

affix attribute

affix: Literal['required', 'omit']
View source

PercentParseResult class

Keep one localized percent edit and its canonical ratio separate.

Attributes

  • input str - The exact user edit.
  • state Literal['valid', 'incomplete', 'invalid'] - valid, incomplete, or invalid.
  • value Decimal | None - The canonical ratio when valid; 0.125 means 12.5 percent.
  • error str | None - A stable explanation for an invalid result, otherwise None.
View source

state attribute

state: Literal['valid', 'incomplete', 'invalid']
View source

valid attribute

valid: bool

Return whether the edit contains one complete percent value.

View source

CurrencyFormat class

Use ICU4X's checked locale-default currency format.

View source

DateFormat class

Format a date and optionally accept input through the same profile.

Attributes

  • length Literal['short', 'medium', 'long'] - The locale-sensitive display length.
  • input DateInput | None - The strict editing rule. None keeps the profile display-only.
View source

DateInput class

Declare how a named date profile accepts editable input.

Attributes

  • mode Literal['strict_text', 'segments'] - "strict_text" accepts one localized date string. "segments" accepts named year, month, and day edit segments.
  • two_digit_year_start int | None - The first year in the selected calendar's explicit 100-year window. None requires a full year.
View source

mode attribute

mode: Literal['strict_text', 'segments']
View source

DateSegments class

Hold the three editable fields from a segmented date control.

Attributes

  • year str - The localized calendar-year edit.
  • month str - The localized numeric month edit.
  • day str - The localized day-of-month edit.
View source

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.

View source

state attribute

state: Literal['valid', 'incomplete', 'invalid', 'ambiguous']
View source

valid attribute

valid: bool

Return whether the edit contains one complete calendar date.

View source

TimeFormat class

Format a wall-clock time and optionally accept localized edits.

Attributes

  • length Literal['short', 'medium', 'long'] - The locale-sensitive display length.
  • input TimeInput | None - The strict editing rule. None keeps the profile display-only.
View source

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.

View source

mode attribute

mode: Literal['strict_text', 'segments']
View source

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.

View source

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.

View source

state attribute

state: Literal['valid', 'incomplete', 'invalid']
View source

valid attribute

valid: bool

Return whether the edit contains one complete wall-clock time.

View source

DateTimeFormat class

Format an instant after conversion to the context's explicit IANA zone.

Attributes

  • length Literal['short', 'medium', 'long'] - The locale-sensitive date and time display length.
  • time_zone_name Literal['none', 'short', 'long'] - Whether and how to display the resolved zone name.
  • input DateTimeInput | None - The strict local-edit rule. None keeps the profile display-only.
View source

length attribute

length: Literal['short', 'medium', 'long']
View source

time_zone_name attribute

time_zone_name: Literal['none', 'short', 'long']
View source

DateTimeInput class

Declare how a named local datetime profile accepts editable input.

Attributes

  • mode Literal['strict_text', 'segments'] - strict_text for one string or segments for named fields.
  • two_digit_year_start int | None - First year in an explicit 100-year window, or None to require a full year.
View source

mode attribute

mode: Literal['strict_text', 'segments']
View source

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.

View source

state attribute

state: Literal['valid', 'incomplete', 'invalid', 'ambiguous']
View source

valid attribute

valid: bool

Return whether the edit resolved to one complete aware instant.

View source

RelativeTimeFormat class

Format a relative day count; the current checked unit is day.

View source

ListFormat class

Format a conjunction or disjunction list.

kind chooses β€œand” or β€œor”. length chooses the locale's wide, short, or narrow pattern.

View source

length attribute

length: Literal['wide', 'short', 'narrow']
View source

UnitFormat class

Format an exact value with an explicit CLDR unit identifier.

Attributes

  • width Literal['long', 'short', 'narrow'] - How fully ICU4X writes the unit name.
View source

width attribute

width: Literal['long', 'short', 'narrow']
View source

I18nError class

Bases: Exception

Base class for i18n errors.

View source

I18nNotConfiguredError class

Bases: I18nError

Raised when an i18n operation needs settings or messages that are absent.

View source

I18nRuntimeUnavailableError class

Bases: I18nError

Raised when the requested i18n operation cannot run in the current context.

Citry version: 0.3.2