# General Translation Python SDKs: t
URL: https://generaltranslation.com/zh/docs/python/reference/functions/t.mdx
Docs index: https://generaltranslation.com/llms.txt
Description: 在 Python 中使用 General Translation 翻译并插值 ICU MessageFormat 字符串。t 的 API 参考。

将 ICU MessageFormat 字符串翻译并插值到当前请求的活动区域设置中。`t` 是主要的面向用户的翻译函数。

## 概览 [#overview]

调用 `t` 时，将源字符串和任意插值变量作为关键字参数传入。它会返回当前区域设置下翻译并插值后的字符串；如果找不到翻译，则回退为插值后的源字符串。

```python
from gt_flask import t  # 或：from gt_fastapi import t，或：from gt_i18n import t

message = t("Hello, {name}!", name="World")
```

签名：

```python
t(message: str, **kwargs: object) -> str
```

*注意：`t` 会读取当前激活的管理器，因此必须先运行 [`initialize_gt`](/docs/python/reference/functions/initialize-gt) (或 [`set_i18n_manager`](/docs/python/reference/functions/set-i18n-manager)) ，否则会引发 `RuntimeError`。*

## 工作原理 [#how-it-works]

* **区域设置检查。** 它从管理器中读取当前区域设置。如果该区域设置无需翻译 (例如，与默认区域设置一致) ，则会跳过查找，只对源文本进行插值。
* **哈希查找。** 否则，它会对消息 (连同 `_context`、`_id` 和 `_max_chars`) 进行哈希处理，然后从内存缓存中读取该区域设置对应的已缓存翻译。该缓存是同步的，因此翻译必须已提前加载——请参阅[预加载](/docs/python/guides/configuring#preload)。
* **插值。** 找到的翻译会使用 ICU MessageFormat，并结合你的变量进行插值，同时将源文本作为 `__fallback`，用于解析已声明的 `_gt_` 变量。
* **后备内容。** 如果未找到翻译，则会对源字符串进行插值并将其返回。

## 参数 [#parameters]

| 参数                    | 描述                       | 类型    | 可选 | 默认值 |
| --------------------- | ------------------------ | ----- | -- | --- |
| [`message`](#message) | ICU MessageFormat 的源字符串。 | `str` | 否  | —   |
| [`kwargs`](#kwargs)   | 插值变量和 GT 的保留选项。          | 关键字参数 | 是  | —   |

### `message` [#message]

**类型** `str` · **必填**

待翻译并进行插值的 ICU MessageFormat 源字符串。

### `kwargs` [#kwargs]

**类型** 关键字参数 · **可选**

与 ICU 占位符对应的插值变量，以及以下这些保留的 GT 选项；这些选项会从插值中排除，并合并到消息 哈希 中：

* `_context` (`str`) — 用于区分具有相同源文本的翻译的附加上下文。
* `_id` (`str`) — 翻译条目的自定义标识符。
* `_max_chars` (`int`) — 应用于输出的最大字符长度。

*名称以单个下划线开头的用户变量 (例如 `_name`) 仍会被视为插值变量；只有上述三个键是保留的。*

## 返回值 [#returns]

**类型** `str`

返回翻译并完成插值的字符串；如果没有可用翻译，则返回插值后的源文本。

## 示例 [#examples]

```python
# 简单翻译
t("Hello, world!")
```

```python
# 使用变量
t("Hello, {name}!", name="Alice")
```

```python
# 使用上下文区分相同的源文本
t("Bank", _context="financial institution")
t("Bank", _context="river bank")
```

```python
# 使用 f-strings 和 declare_var — 包装动态值以确保其被保留
from gt_flask import t, declare_var

# i18n 之前：
message = f"{name} goes home"

# i18n 之后 — 使用 t() 和 declare_var() 包装：
message = t(f"{declare_var(name, name='name')} goes home")
```

```python
# 设置字符上限
t("This is a very long message that might need truncation", _max_chars=20)
```

## Sitemap

See the full [sitemap](https://generaltranslation.com/sitemap.md) for all pages.
