# General Translation Python SDKs: 変数とバリアントの宣言 URL: https://generaltranslation.com/ja/docs/python/guides/declaring-variables.mdx --- title: 変数とバリアントの宣言 description: Python で General Translation の declare_var、derive、decode_vars を使って動的な値を保持し、有限個のバリアントを生成する方法。 related: links: - /docs/python/guides/translating-strings - /docs/python/guides/detecting-locale - /docs/python/guides/configuring - /docs/python/guides/storing-translations --- 翻訳された文字列内の値の中には、その値自体は翻訳すべきでないものがあります。Python SDK にはそのためのマーカーが 2 つあります。1 つは真に動的な値に使う [`declare_var`](/docs/python/reference/functions/declare-var)、もう 1 つは取り得る結果が少数の固定されたものに限られる値に使う [`derive`](/docs/python/reference/functions/derive) です。 ## `declare_var`で動的な値を保持する [#declare-var] ユーザー名、メールアドレス、件数などのランタイム値を `declare_var` で囲むと、その値は翻訳されずにメッセージ内へ埋め込まれたまま保持されます。`declare_var` は ICU の `{_gt_, select, ...}` 構文を返し、それを [`t`](/docs/python/reference/functions/t) 呼び出しの中に配置します。 ```python from gt_flask import t, declare_var t(f"Signed in as {declare_var(email, name='email')}") ``` 省略可能な `name` は、変数に付ける人間が読みやすいラベルで、翻訳者や [`decode_vars`](/docs/python/reference/functions/decode-vars) にとって便利です。 ## `derive` で有限個のバリアントを生成する [#derive] 文の中に、取りうる結果が少数の固定パターンに限られた値が埋め込まれている場合、1回翻訳するだけでは不十分です。ほかの言語では、結果ごとに周囲の語形変化が異なるためです。`derive` はそのような値を示し、CLI が各バリアントに対して個別の翻訳を生成できるようにします。ランタイムでは `derive` は入力値をそのまま返します。抽出時には、CLI が結果ごとに1つのエントリを生成します。 ```python from gt_flask import t, derive gender = "male" t(f"The {derive('boy' if gender == 'male' else 'girl')} is playing.") # 生成: "The boy is playing." と "The girl is playing." ``` 各バリアントはそれぞれ独立して翻訳されるため、どの言語でも自然な表現になります。 *注: 派生される outcome の数はできるだけ少なくしてください。`derive` を追加で呼び出すたびに、生成されるエントリ数が増えていきます。* ## 2つを組み合わせる [#combine] 派生文の中でも、`declare_var` を使えば完全に動的な値を埋め込めるため、翻訳されずにそのまま保持されます。 ```python from gt_flask import t, derive, declare_var t(f"{declare_var(name, name='name')} adopted a {derive('cat' if is_cat else 'dog')}.") ``` ## `decode_vars` で埋め込まれた値を復元する [#decode] [`decode_vars`](/docs/python/reference/functions/decode-vars) は、文字列内の `{_gt_, select, other {value}}` 構文を、その埋め込まれた値に置き換えます。マーク付きの文字列から、値が埋め込まれたプレーンな文字列を取り出したい場合に便利です。 ```python from gt_i18n import declare_var, decode_vars marked = f"Signed in as {declare_var('a@b.com', name='email')}" decode_vars(marked) # "Signed in as a@b.com" ``` *注: [`declare_static`](/docs/python/reference/functions/declare-static) は、後方互換性のために残されている、`derive` の非推奨 alias です。新しいコードでは `derive` を使用してください。* ## Next steps - /docs/python/guides/translating-strings - /docs/python/guides/detecting-locale - /docs/python/guides/configuring - /docs/python/guides/storing-translations