コンテンツにスキップ

Fields

Defining fields on models.

Field

Field(
    default: Any = PydanticUndefined,
    *,
    default_factory: Callable[[], Any] | None = _Unset,
    alias: str | None = _Unset,
    alias_priority: int | None = _Unset,
    validation_alias: (
        str | AliasPath | AliasChoices | None
    ) = _Unset,
    serialization_alias: str | None = _Unset,
    title: str | None = _Unset,
    field_title_generator: (
        Callable[[str, FieldInfo], str] | None
    ) = _Unset,
    description: str | None = _Unset,
    examples: list[Any] | None = _Unset,
    exclude: bool | None = _Unset,
    discriminator: str | Discriminator | None = _Unset,
    deprecated: Deprecated | str | bool | None = _Unset,
    json_schema_extra: (
        JsonDict | Callable[[JsonDict], None] | None
    ) = _Unset,
    frozen: bool | None = _Unset,
    validate_default: bool | None = _Unset,
    repr: bool = _Unset,
    init: bool | None = _Unset,
    init_var: bool | None = _Unset,
    kw_only: bool | None = _Unset,
    pattern: str | Pattern[str] | None = _Unset,
    strict: bool | None = _Unset,
    coerce_numbers_to_str: bool | None = _Unset,
    gt: SupportsGt | None = _Unset,
    ge: SupportsGe | None = _Unset,
    lt: SupportsLt | None = _Unset,
    le: SupportsLe | None = _Unset,
    multiple_of: float | None = _Unset,
    allow_inf_nan: bool | None = _Unset,
    max_digits: int | None = _Unset,
    decimal_places: int | None = _Unset,
    min_length: int | None = _Unset,
    max_length: int | None = _Unset,
    union_mode: Literal["smart", "left_to_right"] = _Unset,
    fail_fast: bool | None = _Unset,
    **extra: Unpack[_EmptyKwargs]
) -> Any

Usage Documentation

Fields

設定可能なオブジェクトのフィールドを作成します。

モデルスキーマまたは複雑な検証のために、フィールドに関する追加情報を提供するために使用されます。引数の中には、数値フィールド(intfloatDecimal)にのみ適用されるものと、strにのみ適用されるものがあります。

Note
  • _Unsetオブジェクトは、_DefaultValues辞書で定義された対応する値に置き換えられます。_Unsetオブジェクトのキーが_DefaultValues辞書で見つからない場合は、デフォルトでNoneになります。

Parameters:

Name Type Description Default
default Any

フィールドが設定されていない場合のデフォルト値。

PydanticUndefined
default_factory Callable[[], Any] | None

:func: ~datetime.utcnowのような、デフォルト値を生成するためにコールできるもの。

_Unset
alias str | None

エイリアスによる検証またはシリアライズ時にアトリビュートに使用する名前。スネークとキャメルケース間の変換などによく使用されます。

_Unset
alias_priority int | None

別名の優先度。別名ジェネレータを使用するかどうかに影響します。

_Unset
validation_alias str | AliasPath | AliasChoices | None

aliasと似ていますが、検証にのみ影響し、シリアライゼーションには影響しません。

_Unset
serialization_alias str | None

aliasと似ていますが、シリアライズにのみ影響し、検証には影響しません。

_Unset
title str | None

人間が読めるタイトル。

_Unset
field_title_generator Callable[[str, FieldInfo], str] | None

フィールド名を受け取り、そのタイトルを返す呼び出し可能オブジェクト。

_Unset
description str | None

人間が読める形式の説明。

_Unset
examples list[Any] | None

このフィールドの値の例。

_Unset
exclude bool | None

モデルのシリアライゼーションからフィールドを除外するかどうか。

_Unset
discriminator str | Discriminator | None

タグ付き共用体の型を識別するためのフィールド名または識別子。

_Unset
deprecated Deprecated | str | bool | None

非推奨メッセージ、warnings.deprecatedまたはtyping_extensions.deprecatedバックポートのインスタンス、またはブール値。Trueの場合、フィールドにアクセスするとデフォルトの非推奨メッセージが出力されます。

_Unset
json_schema_extra JsonDict | Callable[[JsonDict], None] | None

追加のJSONスキーマ・プロパティーを提供するためのdictまたはcallable。

_Unset
frozen bool | None

フィールドが凍結されているかどうか。TRUEの場合、インスタンスの値を変更しようとするとエラーが発生します。

_Unset
validate_default bool | None

Trueの場合、インスタンスを作成するたびにデフォルト値に検証が適用されます。それ以外の場合は、パフォーマンス上の理由から、フィールドのデフォルト値は信頼され、検証されません。

_Unset
repr bool

フィールドを__repr__出力に含めるかどうかを示すブール値です。

_Unset
init bool | None

フィールドをデータクラスのコンストラクタに含めるかどうかを指定します(データクラスにのみ適用されます)。

_Unset
init_var bool | None

データ・クラスのコンストラクタにフィールドを含めるかどうか(データ・クラスにのみ適用)。

_Unset
kw_only bool | None

データクラスのコンストラクタで、フィールドをキーワードのみの引数にするかどうかを指定します(データクラスにのみ適用されます)。

_Unset
coerce_numbers_to_str bool | None

Number型のstrへの強制を有効にするかどうか(strictモードでは適用されません)。

_Unset
strict bool | None

Trueの場合、厳密な検証がフィールドに適用されます。詳細については、Strict Modeを参照してください。

_Unset
gt SupportsGt | None

より大きい。設定する場合、値はこれより大きい必要があります。数値にのみ適用できます。

_Unset
ge SupportsGe | None

以上。設定する場合、値はこれ以上である必要があります。数値にのみ適用できます。

_Unset
lt SupportsLt | None

より小さい。設定する場合、値はこれより小さくする必要があります。数値にのみ適用できます。

_Unset
le SupportsLe | None

以下です。設定する場合、値はこれ以下である必要があります。数値にのみ適用できます。

_Unset
multiple_of float | None

値はこのの倍数である必要があります。数値にのみ適用できます。

_Unset
min_length int | None

iterableの最小長。

_Unset
max_length int | None

iterableの最大長。

_Unset
pattern str | Pattern[str] | None

文字列のパターン(正規表現)。

_Unset
allow_inf_nan bool | None

inf-infnanを許可します。数値にのみ適用されます。

_Unset
max_digits int | None

文字列の最大許容桁数。

_Unset
decimal_places int | None

数値の小数点以下の最大桁数。

_Unset
union_mode Literal['smart', 'left_to_right']

共用体を検証するときに適用される方式。smart(デフォルト)またはleft_to_rightのいずれかです。詳細については、Union Modeを参照してください。

_Unset
fail_fast bool | None

Trueの場合、検証は最初のエラーで停止します。Falseの場合、すべての検証エラーが収集されます。このオプションは、反復可能な型(list、tuple、set、frozenset)にのみ適用できます。

_Unset
extra Unpack[_EmptyKwargs]

(非推奨)JSONスキーマに含まれる追加フィールド。

Warning

extrakwargsは非推奨です。代わりにjson_schema_extraを使用してください。

{}

Returns:

Type Description
Any

新しいFieldInfo。返される注釈はAnyなので、型エラーを起こすことなく型注釈付きのフィールドでFieldを使用できます。

Source code in pydantic/fields.py
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
def Field(  # noqa: C901
    default: Any = PydanticUndefined,
    *,
    default_factory: typing.Callable[[], Any] | None = _Unset,
    alias: str | None = _Unset,
    alias_priority: int | None = _Unset,
    validation_alias: str | AliasPath | AliasChoices | None = _Unset,
    serialization_alias: str | None = _Unset,
    title: str | None = _Unset,
    field_title_generator: typing_extensions.Callable[[str, FieldInfo], str] | None = _Unset,
    description: str | None = _Unset,
    examples: list[Any] | None = _Unset,
    exclude: bool | None = _Unset,
    discriminator: str | types.Discriminator | None = _Unset,
    deprecated: Deprecated | str | bool | None = _Unset,
    json_schema_extra: JsonDict | typing.Callable[[JsonDict], None] | None = _Unset,
    frozen: bool | None = _Unset,
    validate_default: bool | None = _Unset,
    repr: bool = _Unset,
    init: bool | None = _Unset,
    init_var: bool | None = _Unset,
    kw_only: bool | None = _Unset,
    pattern: str | typing.Pattern[str] | None = _Unset,
    strict: bool | None = _Unset,
    coerce_numbers_to_str: bool | None = _Unset,
    gt: annotated_types.SupportsGt | None = _Unset,
    ge: annotated_types.SupportsGe | None = _Unset,
    lt: annotated_types.SupportsLt | None = _Unset,
    le: annotated_types.SupportsLe | None = _Unset,
    multiple_of: float | None = _Unset,
    allow_inf_nan: bool | None = _Unset,
    max_digits: int | None = _Unset,
    decimal_places: int | None = _Unset,
    min_length: int | None = _Unset,
    max_length: int | None = _Unset,
    union_mode: Literal['smart', 'left_to_right'] = _Unset,
    fail_fast: bool | None = _Unset,
    **extra: Unpack[_EmptyKwargs],
) -> Any:
    """Usage docs: https://yodai-yodai.github.io/translated/pydantic-docs-ja/concepts/fields

    設定可能なオブジェクトのフィールドを作成します。

    モデルスキーマまたは複雑な検証のために、フィールドに関する追加情報を提供するために使用されます。引数の中には、数値フィールド(`int`、`float`、`Decimal`)にのみ適用されるものと、`str`にのみ適用されるものがあります。

    Note:
        - `_Unset`オブジェクトは、`_DefaultValues`辞書で定義された対応する値に置き換えられます。`_Unset`オブジェクトのキーが`_DefaultValues`辞書で見つからない場合は、デフォルトで`None`になります。

    Args:
        default: フィールドが設定されていない場合のデフォルト値。
        default_factory: :func: `~datetime.utcnow`のような、デフォルト値を生成するためにコールできるもの。
        alias: エイリアスによる検証またはシリアライズ時にアトリビュートに使用する名前。スネークとキャメルケース間の変換などによく使用されます。
        alias_priority: 別名の優先度。別名ジェネレータを使用するかどうかに影響します。
        validation_alias: `alias`と似ていますが、検証にのみ影響し、シリアライゼーションには影響しません。
        serialization_alias: `alias`と似ていますが、シリアライズにのみ影響し、検証には影響しません。
        title: 人間が読めるタイトル。
        field_title_generator: フィールド名を受け取り、そのタイトルを返す呼び出し可能オブジェクト。
        description: 人間が読める形式の説明。
        examples: このフィールドの値の例。
        exclude: モデルのシリアライゼーションからフィールドを除外するかどうか。
        discriminator: タグ付き共用体の型を識別するためのフィールド名または識別子。
        deprecated: 非推奨メッセージ、`warnings.deprecated`または`typing_extensions.deprecated`バックポートのインスタンス、またはブール値。`True`の場合、フィールドにアクセスするとデフォルトの非推奨メッセージが出力されます。
        json_schema_extra: 追加のJSONスキーマ・プロパティーを提供するためのdictまたはcallable。
        frozen: フィールドが凍結されているかどうか。TRUEの場合、インスタンスの値を変更しようとするとエラーが発生します。
        validate_default: `True`の場合、インスタンスを作成するたびにデフォルト値に検証が適用されます。それ以外の場合は、パフォーマンス上の理由から、フィールドのデフォルト値は信頼され、検証されません。
        repr: フィールドを`__repr__`出力に含めるかどうかを示すブール値です。
        init: フィールドをデータクラスのコンストラクタに含めるかどうかを指定します(データクラスにのみ適用されます)。
        init_var: データ・クラスのコンストラクタにフィールドを含めるかどうか(データ・クラスにのみ適用)。
        kw_only: データクラスのコンストラクタで、フィールドをキーワードのみの引数にするかどうかを指定します(データクラスにのみ適用されます)。
        coerce_numbers_to_str: `Number`型の`str`への強制を有効にするかどうか(`strict`モードでは適用されません)。
        strict: `True`の場合、厳密な検証がフィールドに適用されます。詳細については、[Strict Mode](https://yodai-yodai.github.io/translated/pydantic-docs-ja/concepts/strict_mode.md)を参照してください。
        gt: より大きい。設定する場合、値はこれより大きい必要があります。数値にのみ適用できます。
        ge: 以上。設定する場合、値はこれ以上である必要があります。数値にのみ適用できます。
        lt: より小さい。設定する場合、値はこれより小さくする必要があります。数値にのみ適用できます。
        le: 以下です。設定する場合、値はこれ以下である必要があります。数値にのみ適用できます。
        multiple_of: 値はこのの倍数である必要があります。数値にのみ適用できます。
        min_length: iterableの最小長。
        max_length: iterableの最大長。
        pattern: 文字列のパターン(正規表現)。
        allow_inf_nan: `inf`、`-inf`、`nan`を許可します。数値にのみ適用されます。
        max_digits: 文字列の最大許容桁数。
        decimal_places: 数値の小数点以下の最大桁数。
        union_mode: 共用体を検証するときに適用される方式。`smart`(デフォルト)または`left_to_right`のいずれかです。詳細については、[Union Mode](https://yodai-yodai.github.io/translated/pydantic-docs-ja/concepts/unions.md#union-modes)を参照してください。
        fail_fast: `True`の場合、検証は最初のエラーで停止します。`False`の場合、すべての検証エラーが収集されます。このオプションは、反復可能な型(list、tuple、set、frozenset)にのみ適用できます。
        extra: (非推奨)JSONスキーマに含まれる追加フィールド。

            !!! warning Deprecated
                `extra`kwargsは非推奨です。代わりに`json_schema_extra`を使用してください。

    Returns:
        新しい[`FieldInfo`][pydantic.fields.FieldInfo]。返される注釈は`Any`なので、型エラーを起こすことなく型注釈付きのフィールドで`Field`を使用できます。
    """
    # Check deprecated and removed params from V1. This logic should eventually be removed.
    const = extra.pop('const', None)  # type: ignore
    if const is not None:
        raise PydanticUserError('`const` is removed, use `Literal` instead', code='removed-kwargs')

    min_items = extra.pop('min_items', None)  # type: ignore
    if min_items is not None:
        warn('`min_items` is deprecated and will be removed, use `min_length` instead', DeprecationWarning)
        if min_length in (None, _Unset):
            min_length = min_items  # type: ignore

    max_items = extra.pop('max_items', None)  # type: ignore
    if max_items is not None:
        warn('`max_items` is deprecated and will be removed, use `max_length` instead', DeprecationWarning)
        if max_length in (None, _Unset):
            max_length = max_items  # type: ignore

    unique_items = extra.pop('unique_items', None)  # type: ignore
    if unique_items is not None:
        raise PydanticUserError(
            (
                '`unique_items` is removed, use `Set` instead'
                '(this feature is discussed in https://github.com/pydantic/pydantic-core/issues/296)'
            ),
            code='removed-kwargs',
        )

    allow_mutation = extra.pop('allow_mutation', None)  # type: ignore
    if allow_mutation is not None:
        warn('`allow_mutation` is deprecated and will be removed. use `frozen` instead', DeprecationWarning)
        if allow_mutation is False:
            frozen = True

    regex = extra.pop('regex', None)  # type: ignore
    if regex is not None:
        raise PydanticUserError('`regex` is removed. use `pattern` instead', code='removed-kwargs')

    if extra:
        warn(
            'Using extra keyword arguments on `Field` is deprecated and will be removed.'
            ' Use `json_schema_extra` instead.'
            f' (Extra keys: {", ".join(k.__repr__() for k in extra.keys())})',
            DeprecationWarning,
        )
        if not json_schema_extra or json_schema_extra is _Unset:
            json_schema_extra = extra  # type: ignore

    if (
        validation_alias
        and validation_alias is not _Unset
        and not isinstance(validation_alias, (str, AliasChoices, AliasPath))
    ):
        raise TypeError('Invalid `validation_alias` type. it should be `str`, `AliasChoices`, or `AliasPath`')

    if serialization_alias in (_Unset, None) and isinstance(alias, str):
        serialization_alias = alias

    if validation_alias in (_Unset, None):
        validation_alias = alias

    include = extra.pop('include', None)  # type: ignore
    if include is not None:
        warn('`include` is deprecated and does nothing. It will be removed, use `exclude` instead', DeprecationWarning)

    return FieldInfo.from_field(
        default,
        default_factory=default_factory,
        alias=alias,
        alias_priority=alias_priority,
        validation_alias=validation_alias,
        serialization_alias=serialization_alias,
        title=title,
        field_title_generator=field_title_generator,
        description=description,
        examples=examples,
        exclude=exclude,
        discriminator=discriminator,
        deprecated=deprecated,
        json_schema_extra=json_schema_extra,
        frozen=frozen,
        pattern=pattern,
        validate_default=validate_default,
        repr=repr,
        init=init,
        init_var=init_var,
        kw_only=kw_only,
        coerce_numbers_to_str=coerce_numbers_to_str,
        strict=strict,
        gt=gt,
        ge=ge,
        lt=lt,
        le=le,
        multiple_of=multiple_of,
        min_length=min_length,
        max_length=max_length,
        allow_inf_nan=allow_inf_nan,
        max_digits=max_digits,
        decimal_places=decimal_places,
        union_mode=union_mode,
        fail_fast=fail_fast,
    )

FieldInfo

FieldInfo(**kwargs: Unpack[_FieldInfoInputs])

Bases: Representation

このクラスはフィールドに関する情報を保持します。

FieldInfoは、Field()関数が明示的に使用されているかどうかにかかわらず、すべてのフィールド定義に使用されます。

Warning

一般的にはFieldInfoを直接作成すべきではありません。BaseModel.model_fields内部にアクセスするときにのみ使用する必要があります。

Attributes:

Name Type Description
annotation type[Any] | None

フィールドの型注釈。

default Any

フィールドのデフォルト値。

default_factory Callable[[], Any] | None

フィールドのデフォルトを構成するために使用されるファクトリ関数。

alias str | None

フィールドのエイリアス名。

alias_priority int | None

フィールドのエイリアスの優先度。

validation_alias str | AliasPath | AliasChoices | None

フィールドの検証エイリアス。

serialization_alias str | None

フィールドのシリアル化エイリアス。

title str | None

フィールドのタイトル。

field_title_generator Callable[[str, FieldInfo], str] | None

フィールド名を受け取り、そのタイトルを返す呼び出し可能オブジェクト。

description str | None

フィールドの説明。

examples list[Any] | None

フィールドの例のリスト。

exclude bool | None

モデルのシリアライゼーションからフィールドを除外するかどうか。

discriminator str | Discriminator | None

タグ付き共用体の型を識別するためのフィールド名または識別子。

deprecated Deprecated | str | bool | None

非推奨メッセージ、warnings.deprecatedまたはtyping_extensions.deprecatedバックポートのインスタンス、またはブール値。Trueの場合、フィールドにアクセスするとデフォルトの非推奨メッセージが出力されます。

json_schema_extra JsonDict | Callable[[JsonDict], None] | None

追加のJSONスキーマ・プロパティーを提供するためのdictまたはcallable。

frozen bool | None

フィールドが凍結されているかどうか。

validate_default bool | None

フィールドのデフォルト値を検証するかどうか。

repr bool

モデルの表現にフィールドを含めるかどうか。

init bool | None

フィールドをデータクラスのコンストラクタに含めるかどうか。

init_var bool | None

フィールドがデータ・クラスのコンストラクターに含まれ、保管されないようにするかどうか。

kw_only bool | None

データクラスのコンストラクタで、フィールドをキーワードのみの引数にするかどうか。

metadata list[Any]

メタデータ制約のリスト。

期待される引数の詳細については、pydantic.fields.Fieldのシグネチャを参照してください。

Source code in pydantic/fields.py
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
def __init__(self, **kwargs: Unpack[_FieldInfoInputs]) -> None:
    """このクラスは通常、直接初期化すべきではありません。代わりに、`pydantic.fields.Field`関数またはコンストラクタクラスメソッドの1つを使用してください。

    期待される引数の詳細については、`pydantic.fields.Field`のシグネチャを参照してください。
    """
    self._attributes_set = {k: v for k, v in kwargs.items() if v is not _Unset}
    kwargs = {k: _DefaultValues.get(k) if v is _Unset else v for k, v in kwargs.items()}  # type: ignore
    self.annotation, annotation_metadata = self._extract_metadata(kwargs.get('annotation'))

    default = kwargs.pop('default', PydanticUndefined)
    if default is Ellipsis:
        self.default = PydanticUndefined
    else:
        self.default = default

    self.default_factory = kwargs.pop('default_factory', None)

    if self.default is not PydanticUndefined and self.default_factory is not None:
        raise TypeError('cannot specify both default and default_factory')

    self.alias = kwargs.pop('alias', None)
    self.validation_alias = kwargs.pop('validation_alias', None)
    self.serialization_alias = kwargs.pop('serialization_alias', None)
    alias_is_set = any(alias is not None for alias in (self.alias, self.validation_alias, self.serialization_alias))
    self.alias_priority = kwargs.pop('alias_priority', None) or 2 if alias_is_set else None
    self.title = kwargs.pop('title', None)
    self.field_title_generator = kwargs.pop('field_title_generator', None)
    self.description = kwargs.pop('description', None)
    self.examples = kwargs.pop('examples', None)
    self.exclude = kwargs.pop('exclude', None)
    self.discriminator = kwargs.pop('discriminator', None)
    # For compatibility with FastAPI<=0.110.0, we preserve the existing value if it is not overridden
    self.deprecated = kwargs.pop('deprecated', getattr(self, 'deprecated', None))
    self.repr = kwargs.pop('repr', True)
    self.json_schema_extra = kwargs.pop('json_schema_extra', None)
    self.validate_default = kwargs.pop('validate_default', None)
    self.frozen = kwargs.pop('frozen', None)
    # currently only used on dataclasses
    self.init = kwargs.pop('init', None)
    self.init_var = kwargs.pop('init_var', None)
    self.kw_only = kwargs.pop('kw_only', None)

    self.metadata = self._collect_metadata(kwargs) + annotation_metadata  # type: ignore

from_field staticmethod

from_field(
    default: Any = PydanticUndefined,
    **kwargs: Unpack[_FromFieldInfoInputs]
) -> FieldInfo

Field関数を使用して新しいFieldInfoオブジェクトを作成します。

Parameters:

Name Type Description Default
default Any

フィールドのデフォルト値。デフォルトは"未定義"です。

PydanticUndefined
**kwargs Unpack[_FromFieldInfoInputs]

追加引数の辞書。

{}

Raises:

Type Description
TypeError

'annotation'がキーワード引数として渡された場合。

Returns:

Type Description
FieldInfo

指定されたパラメータを持つ新しいFieldInfoオブジェクト。

Example

次のようにして、デフォルト値を持つフィールドを作成できます。

import pydantic

class MyModel(pydantic.BaseModel):
    foo: int = pydantic.Field(4)
Source code in pydantic/fields.py
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
@staticmethod
def from_field(default: Any = PydanticUndefined, **kwargs: Unpack[_FromFieldInfoInputs]) -> FieldInfo:
    """`Field`関数を使用して新しい`FieldInfo`オブジェクトを作成します。

    Args:
        default: フィールドのデフォルト値。デフォルトは"未定義"です。
        **kwargs: 追加引数の辞書。

    Raises:
        TypeError: 'annotation'がキーワード引数として渡された場合。

    Returns:
        指定されたパラメータを持つ新しいFieldInfoオブジェクト。

    Example:
        次のようにして、デフォルト値を持つフィールドを作成できます。

        ```python
        import pydantic

        class MyModel(pydantic.BaseModel):
            foo: int = pydantic.Field(4)
        ```
    """
    if 'annotation' in kwargs:
        raise TypeError('"annotation" is not permitted as a Field keyword argument')
    return FieldInfo(default=default, **kwargs)

from_annotation staticmethod

from_annotation(annotation: type[Any]) -> FieldInfo

生の注釈からFieldInfoインスタンスを作成します。

この関数は、次のような生の注釈からFieldInfoを作成するために内部的に使用されます。

import pydantic

class MyModel(pydantic.BaseModel):
    foo: int  # <-- like this

また、注釈がAnnotatedのインスタンスである可能性があり、Annotatedの(最初ではない)引数の1つがFieldInfoのインスタンスである場合についても説明します。次に例を示します。

import annotated_types
from typing_extensions import Annotated

import pydantic

class MyModel(pydantic.BaseModel):
    foo: Annotated[int, annotated_types.Gt(42)]
    bar: Annotated[int, pydantic.Field(gt=42)]

Parameters:

Name Type Description Default
annotation type[Any]

注釈オブジェクト。

required

Returns:

Type Description
FieldInfo

フィールドメタデータのインスタンス。

Source code in pydantic/fields.py
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
@staticmethod
def from_annotation(annotation: type[Any]) -> FieldInfo:
    """生の注釈から`FieldInfo`インスタンスを作成します。

    この関数は、次のような生の注釈から`FieldInfo`を作成するために内部的に使用されます。

    ```python
    import pydantic

    class MyModel(pydantic.BaseModel):
        foo: int  # <-- like this
    ```

    また、注釈が`Annotated`のインスタンスである可能性があり、`Annotated`の(最初ではない)引数の1つが`FieldInfo`のインスタンスである場合についても説明します。次に例を示します。

    ```python
    import annotated_types
    from typing_extensions import Annotated

    import pydantic

    class MyModel(pydantic.BaseModel):
        foo: Annotated[int, annotated_types.Gt(42)]
        bar: Annotated[int, pydantic.Field(gt=42)]
    ```

    Args:
        annotation: 注釈オブジェクト。

    Returns:
        フィールドメタデータのインスタンス。
    """
    final = False
    if _typing_extra.is_finalvar(annotation):
        final = True
        if annotation is not typing_extensions.Final:
            annotation = typing_extensions.get_args(annotation)[0]

    if _typing_extra.is_annotated(annotation):
        first_arg, *extra_args = typing_extensions.get_args(annotation)
        if _typing_extra.is_finalvar(first_arg):
            final = True
        field_info_annotations = [a for a in extra_args if isinstance(a, FieldInfo)]
        field_info = FieldInfo.merge_field_infos(*field_info_annotations, annotation=first_arg)
        if field_info:
            new_field_info = copy(field_info)
            new_field_info.annotation = first_arg
            new_field_info.frozen = final or field_info.frozen
            metadata: list[Any] = []
            for a in extra_args:
                if _typing_extra.is_deprecated_instance(a):
                    new_field_info.deprecated = a.message
                elif not isinstance(a, FieldInfo):
                    metadata.append(a)
                else:
                    metadata.extend(a.metadata)
            new_field_info.metadata = metadata
            return new_field_info

    return FieldInfo(annotation=annotation, frozen=final or None)  # pyright: ignore[reportArgumentType]

from_annotated_attribute staticmethod

from_annotated_attribute(
    annotation: type[Any], default: Any
) -> FieldInfo

デフォルト値を持つ注釈からFieldInfoを作成します。

これは、次のような場合に使用されます。

import annotated_types
from typing_extensions import Annotated

import pydantic

class MyModel(pydantic.BaseModel):
    foo: int = 4  # <-- like this
    bar: Annotated[int, annotated_types.Gt(4)] = 4  # <-- or this
    spam: Annotated[int, pydantic.Field(gt=4)] = 4  # <-- or this

Parameters:

Name Type Description Default
annotation type[Any]

フィールドの型注釈。

required
default Any

フィールドのデフォルト値。

required

Returns:

Type Description
FieldInfo

渡された値を持つフィールド・オブジェクト。

Source code in pydantic/fields.py
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
@staticmethod
def from_annotated_attribute(annotation: type[Any], default: Any) -> FieldInfo:
    """デフォルト値を持つ注釈から`FieldInfo`を作成します。

    これは、次のような場合に使用されます。

    ```python
    import annotated_types
    from typing_extensions import Annotated

    import pydantic

    class MyModel(pydantic.BaseModel):
        foo: int = 4  # <-- like this
        bar: Annotated[int, annotated_types.Gt(4)] = 4  # <-- or this
        spam: Annotated[int, pydantic.Field(gt=4)] = 4  # <-- or this
    ```

    Args:
        annotation: フィールドの型注釈。
        default: フィールドのデフォルト値。

    Returns:
        渡された値を持つフィールド・オブジェクト。
    """
    if annotation is default:
        raise PydanticUserError(
            'Error when building FieldInfo from annotated attribute. '
            "Make sure you don't have any field name clashing with a type annotation ",
            code='unevaluable-type-annotation',
        )

    final = False
    if _typing_extra.is_finalvar(annotation):
        final = True
        if annotation is not typing_extensions.Final:
            annotation = typing_extensions.get_args(annotation)[0]

    if isinstance(default, FieldInfo):
        default.annotation, annotation_metadata = FieldInfo._extract_metadata(annotation)  # pyright: ignore[reportArgumentType]
        default.metadata += annotation_metadata
        default = default.merge_field_infos(
            *[x for x in annotation_metadata if isinstance(x, FieldInfo)], default, annotation=default.annotation
        )
        default.frozen = final or default.frozen
        return default
    elif isinstance(default, dataclasses.Field):
        init_var = False
        if annotation is dataclasses.InitVar:
            init_var = True
            annotation = typing.cast(Any, Any)
        elif isinstance(annotation, dataclasses.InitVar):
            init_var = True
            annotation = annotation.type
        pydantic_field = FieldInfo._from_dataclass_field(default)
        pydantic_field.annotation, annotation_metadata = FieldInfo._extract_metadata(annotation)  # pyright: ignore[reportArgumentType]
        pydantic_field.metadata += annotation_metadata
        pydantic_field = pydantic_field.merge_field_infos(
            *[x for x in annotation_metadata if isinstance(x, FieldInfo)],
            pydantic_field,
            annotation=pydantic_field.annotation,
        )
        pydantic_field.frozen = final or pydantic_field.frozen
        pydantic_field.init_var = init_var
        pydantic_field.init = getattr(default, 'init', None)
        pydantic_field.kw_only = getattr(default, 'kw_only', None)
        return pydantic_field
    else:
        if _typing_extra.is_annotated(annotation):
            first_arg, *extra_args = typing_extensions.get_args(annotation)
            field_infos = [a for a in extra_args if isinstance(a, FieldInfo)]
            field_info = FieldInfo.merge_field_infos(*field_infos, annotation=first_arg, default=default)
            metadata: list[Any] = []
            for a in extra_args:
                if _typing_extra.is_deprecated_instance(a):
                    field_info.deprecated = a.message
                elif not isinstance(a, FieldInfo):
                    metadata.append(a)
                else:
                    metadata.extend(a.metadata)
            field_info.metadata = metadata
            return field_info

        return FieldInfo(annotation=annotation, default=default, frozen=final or None)  # pyright: ignore[reportArgumentType]

merge_field_infos staticmethod

merge_field_infos(
    *field_infos: FieldInfo, **overrides: Any
) -> FieldInfo

明示的に設定された属性のみを保持してFieldInfoインスタンスをマージします。

後のFieldInfoインスタンスは前のインスタンスを上書きします。

Returns:

Name Type Description
FieldInfo FieldInfo

マージされたFieldInfoインスタンス。

Source code in pydantic/fields.py
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
@staticmethod
def merge_field_infos(*field_infos: FieldInfo, **overrides: Any) -> FieldInfo:
    """明示的に設定された属性のみを保持して`FieldInfo`インスタンスをマージします。

    後の`FieldInfo`インスタンスは前のインスタンスを上書きします。

    Returns:
        FieldInfo: マージされたFieldInfoインスタンス。
    """
    flattened_field_infos: list[FieldInfo] = []
    for field_info in field_infos:
        flattened_field_infos.extend(x for x in field_info.metadata if isinstance(x, FieldInfo))
        flattened_field_infos.append(field_info)
    field_infos = tuple(flattened_field_infos)
    if len(field_infos) == 1:
        # No merging necessary, but we still need to make a copy and apply the overrides
        field_info = copy(field_infos[0])
        field_info._attributes_set.update(overrides)

        default_override = overrides.pop('default', PydanticUndefined)
        if default_override is Ellipsis:
            default_override = PydanticUndefined
        if default_override is not PydanticUndefined:
            field_info.default = default_override

        for k, v in overrides.items():
            setattr(field_info, k, v)
        return field_info  # type: ignore

    merged_field_info_kwargs: dict[str, Any] = {}
    metadata = {}
    for field_info in field_infos:
        attributes_set = field_info._attributes_set.copy()

        try:
            json_schema_extra = attributes_set.pop('json_schema_extra')
            existing_json_schema_extra = merged_field_info_kwargs.get('json_schema_extra', {})

            if isinstance(existing_json_schema_extra, dict) and isinstance(json_schema_extra, dict):
                merged_field_info_kwargs['json_schema_extra'] = {**existing_json_schema_extra, **json_schema_extra}
            else:
                # if ever there's a case of a callable, we'll just keep the last json schema extra spec
                merged_field_info_kwargs['json_schema_extra'] = json_schema_extra
        except KeyError:
            pass

        # later FieldInfo instances override everything except json_schema_extra from earlier FieldInfo instances
        merged_field_info_kwargs.update(attributes_set)

        for x in field_info.metadata:
            if not isinstance(x, FieldInfo):
                metadata[type(x)] = x

    merged_field_info_kwargs.update(overrides)
    field_info = FieldInfo(**merged_field_info_kwargs)
    field_info.metadata = list(metadata.values())
    return field_info

deprecation_message property

deprecation_message: str | None

発行される非推奨メッセージ、または設定されていない場合はNone

get_default

get_default(*, call_default_factory: bool = False) -> Any

デフォルト値を取得します。

default_factoryを呼び出すと、回避したい副作用が発生する可能性があるため、default_factory(存在する場合)を呼び出すかどうかのオプションを公開します。ただし、実際に呼び出す必要がある場合もあります(つまり、model_constructを使用してモデルをインスタンス化する場合)。

Parameters:

Name Type Description Default
call_default_factory bool

default_factoryを呼び出すかどうか。デフォルトはFalseです。

False

Returns:

Type Description
Any

デフォルト値。要求された場合はデフォルトのファクトリを呼び出し、設定されていない場合はNoneを呼び出します。

Source code in pydantic/fields.py
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
def get_default(self, *, call_default_factory: bool = False) -> Any:
    """デフォルト値を取得します。

    default_factoryを呼び出すと、回避したい副作用が発生する可能性があるため、default_factory(存在する場合)を呼び出すかどうかのオプションを公開します。ただし、実際に呼び出す必要がある場合もあります(つまり、`model_construct`を使用してモデルをインスタンス化する場合)。

    Args:
        call_default_factory:default_factoryを呼び出すかどうか。デフォルトは`False`です。

    Returns:
        デフォルト値。要求された場合はデフォルトのファクトリを呼び出し、設定されていない場合は`None`を呼び出します。
    """
    if self.default_factory is None:
        return _utils.smart_deepcopy(self.default)
    elif call_default_factory:
        return self.default_factory()
    else:
        return None

is_required

is_required() -> bool

フィールドが必要かどうかをチェックしてください(デフォルト値またはファクトリがないなど)。

Returns:

Type Description
bool

フィールドが必要な場合はTrue、そうでない場合はFalseです。

Source code in pydantic/fields.py
568
569
570
571
572
573
574
def is_required(self) -> bool:
    """フィールドが必要かどうかをチェックしてください(デフォルト値またはファクトリがないなど)。

    Returns:
        フィールドが必要な場合は`True`、そうでない場合は`False`です。
    """
    return self.default is PydanticUndefined and self.default_factory is None

rebuild_annotation

rebuild_annotation() -> Any

関数シグネチャで使用するために元の注釈を再構築しようとします。

メタデータが存在する場合は、Annotatedを使用して元の注釈に追加します。存在しない場合は、元の注釈をそのまま返します。

メタデータがフラット化されているため、元の型に認識されないアノテーションがあったり、pydantic.Fieldを呼び出してアノテーションが付けられたりした場合など、元のアノテーションが元のまま正確に再構築されない可能性があることに注意してください。

Returns:

Type Description
Any

再構築された注釈。

Source code in pydantic/fields.py
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
def rebuild_annotation(self) -> Any:
    """関数シグネチャで使用するために元の注釈を再構築しようとします。

    メタデータが存在する場合は、`Annotated`を使用して元の注釈に追加します。存在しない場合は、元の注釈をそのまま返します。

    メタデータがフラット化されているため、元の型に認識されないアノテーションがあったり、`pydantic.Field`を呼び出してアノテーションが付けられたりした場合など、元のアノテーションが元のまま正確に再構築されない可能性があることに注意してください。

    Returns:
        再構築された注釈。
    """
    if not self.metadata:
        return self.annotation
    else:
        # Annotated arguments must be a tuple
        return typing_extensions.Annotated[(self.annotation, *self.metadata)]  # type: ignore

apply_typevars_map

apply_typevars_map(
    typevars_map: dict[Any, Any] | None,
    types_namespace: dict[str, Any] | None,
) -> None

注釈にtypevars_mapを適用してください。

このメソッドは、パラメータ化されたジェネリック型を分析して、型変数を具体的な型に置き換えるときに使用されます。

このメソッドは、typevars_mapをアノテーションにインプレイスで適用します。

Parameters:

Name Type Description Default
typevars_map dict[Any, Any] | None

型変数をその具象型にマップする辞書。

required
types_namespace dict[str, Any] | None

アノテーションが付けられた型に関連する型を含む辞書。

required
See Also

pydantic._internal._generics.replace_typesは、typevarを具象型に置き換えるために使用されます。

Source code in pydantic/fields.py
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
def apply_typevars_map(self, typevars_map: dict[Any, Any] | None, types_namespace: dict[str, Any] | None) -> None:
    """注釈に`typevars_map`を適用してください。

    このメソッドは、パラメータ化されたジェネリック型を分析して、型変数を具体的な型に置き換えるときに使用されます。

    このメソッドは、`typevars_map`をアノテーションにインプレイスで適用します。

    Args:
        typevars_map: 型変数をその具象型にマップする辞書。
        types_namespace: アノテーションが付けられた型に関連する型を含む辞書。

    See Also:
        pydantic._internal._generics.replace_typesは、typevarを具象型に置き換えるために使用されます。
    """
    annotation = _typing_extra.eval_type_lenient(self.annotation, types_namespace)
    self.annotation = _generics.replace_types(annotation, typevars_map)

PrivateAttr

PrivateAttr(
    default: Any = PydanticUndefined,
    *,
    default_factory: Callable[[], Any] | None = None,
    init: Literal[False] = False
) -> Any

Usage Documentation

Private model attributes

属性がプライベートに使用され、通常の検証/シリアライゼーションでは処理されないことを示します。

private属性はPydanticによって検証されないため、タイプセーフな方法で使用するかどうかはユーザー次第です。

プライベート属性は、モデルの__private_attributes__に保存されます。

Parameters:

Name Type Description Default
default Any

属性のデフォルト値。デフォルトは"未定義"です。

PydanticUndefined
default_factory Callable[[], Any] | None

この属性にデフォルト値が必要な場合に呼び出される呼び出し可能オブジェクト。defaultdefault_factoryの両方が設定されている場合、エラーが発生します。

None
init Literal[False]

属性をデータクラスのコンストラクタに含めるかどうか。常にFalseです。

False

Returns:

Type Description
Any

ModelPrivateAttrクラスのインスタンスです。

Raises:

Type Description
ValueError

defaultdefault_factoryの両方が設定されている場合。

Source code in pydantic/fields.py
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
def PrivateAttr(
    default: Any = PydanticUndefined,
    *,
    default_factory: typing.Callable[[], Any] | None = None,
    init: Literal[False] = False,
) -> Any:
    """Usage docs: https://yodai-yodai.github.io/translated/pydantic-docs-ja/concepts/models/#private-model-attributes

    属性がプライベートに使用され、通常の検証/シリアライゼーションでは処理されないことを示します。

    private属性はPydanticによって検証されないため、タイプセーフな方法で使用するかどうかはユーザー次第です。

    プライベート属性は、モデルの`__private_attributes__`に保存されます。

    Args:
        default: 属性のデフォルト値。デフォルトは"未定義"です。
        default_factory: この属性にデフォルト値が必要な場合に呼び出される呼び出し可能オブジェクト。`default`と`default_factory`の両方が設定されている場合、エラーが発生します。
        init: 属性をデータクラスのコンストラクタに含めるかどうか。常に`False`です。

    Returns:
        [`ModelPrivateAttr`][pydantic.fields.ModelPrivateAttr]クラスのインスタンスです。

    Raises:
        ValueError: `default`と`default_factory`の両方が設定されている場合。
    """
    if default is not PydanticUndefined and default_factory is not None:
        raise TypeError('cannot specify both default and default_factory')

    return ModelPrivateAttr(
        default,
        default_factory=default_factory,
    )

ModelPrivateAttr

ModelPrivateAttr(
    default: Any = PydanticUndefined,
    *,
    default_factory: Callable[[], Any] | None = None
)

Bases: Representation

クラスモデル内のプライベート属性の記述子。

Warning

一般的に、ModelPrivateAttrインスタンスを直接作成すべきではなく、代わりにpydantic.fields.PrivateAttrを使用してください(これはFieldInfoFieldに似ています)。

Attributes:

Name Type Description
default

属性のデフォルト値(指定されていない場合)。

default_factory

指定されていない場合に属性のデフォルト値を生成する、呼び出し可能な関数。

Source code in pydantic/fields.py
889
890
891
892
893
def __init__(
    self, default: Any = PydanticUndefined, *, default_factory: typing.Callable[[], Any] | None = None
) -> None:
    self.default = default
    self.default_factory = default_factory

get_default

get_default() -> Any

オブジェクトのデフォルト値を取得します。

self.default_factoryNoneの場合、このメソッドはself.defaultオブジェクトのディープコピーを返します。

self.default_factoryNoneでない場合、self.default_factoryを呼び出し、返された値を返します。

Returns:

Type Description
Any

オブジェクトのデフォルト値。

Source code in pydantic/fields.py
916
917
918
919
920
921
922
923
924
925
926
def get_default(self) -> Any:
    """オブジェクトのデフォルト値を取得します。

    `self.default_factory`が`None`の場合、このメソッドは`self.default`オブジェクトのディープコピーを返します。

    `self.default_factory`が`None`でない場合、`self.default_factory`を呼び出し、返された値を返します。

    Returns:
        オブジェクトのデフォルト値。
    """
    return _utils.smart_deepcopy(self.default) if self.default_factory is None else self.default_factory()

computed_field

computed_field(
    func: PropertyT | None = None,
    /,
    *,
    alias: str | None = None,
    alias_priority: int | None = None,
    title: str | None = None,
    field_title_generator: (
        Callable[[str, ComputedFieldInfo], str] | None
    ) = None,
    description: str | None = None,
    deprecated: Deprecated | str | bool | None = None,
    examples: list[Any] | None = None,
    json_schema_extra: (
        JsonDict | Callable[[JsonDict], None] | None
    ) = None,
    repr: bool | None = None,
    return_type: Any = PydanticUndefined,
) -> PropertyT | Callable[[PropertyT], PropertyT]

Usage Documentation

The computed_field decorator

モデルまたはデータクラスをシリアライズするときにpropertycached_propertyを含めるデコレータ。

これは、他のフィールドから計算されるフィールドや、計算にコストがかかり、キャッシュする必要があるフィールドに便利です。

from pydantic import BaseModel, computed_field

class Rectangle(BaseModel):
    width: int
    length: int

    @computed_field
    @property
    def area(self) -> int:
        return self.width * self.length

print(Rectangle(width=3, length=2).model_dump())
#> {'width': 3, 'length': 2, 'area': 6}

@propertyまたは@cached_propertyでデコレートされていない関数に適用すると、その関数は自動的にpropertyでラップされます。 これはより簡潔ですが、IDE内のIntelliSenseが失われ、静的型チェッカーが混乱するため、@propertyを明示的に使用することをお勧めします。

Mypy Warning

@computed_fieldの前に@propertyまたは@cached_propertyを関数に適用しても、mypyはDecorated property not supportedエラーをスローすることがあります。 詳細については、mypy issue #1362を参照してください。 このエラーメッセージを回避するには、@computed_field行に#type:ignore[misc]を追加してください。

pyrightはエラーなしで@computed_fieldをサポートしています。

import random

from pydantic import BaseModel, computed_field

class Square(BaseModel):
    width: float

    @computed_field
    def area(self) -> float:  # converted to a `property` by `computed_field`
        return round(self.width**2, 2)

    @area.setter
    def area(self, new_area: float) -> None:
        self.width = new_area**0.5

    @computed_field(alias='the magic number', repr=False)
    def random_number(self) -> int:
        return random.randint(0, 1_000)

square = Square(width=1.3)

# `random_number` does not appear in representation
print(repr(square))
#> Square(width=1.3, area=1.69)

print(square.random_number)
#> 3

square.area = 4

print(square.model_dump_json(by_alias=True))
#> {"width":2.0,"area":4.0,"the magic number":3}

Overriding with computed_field

親クラスのフィールドを子クラスのcomputed_fieldで上書きすることはできません。 mypyは許可されていればこのふるまいは許しませんし、dataclassesもこのパターンを許可していません。 次の例を参照してください。

from pydantic import BaseModel, computed_field

class Parent(BaseModel):
    a: str

try:

    class Child(Parent):
        @computed_field
        @property
        def a(self) -> str:
            return 'new a'

except ValueError as e:
    print(repr(e))
    #> ValueError("you can't override a field with a computed field")

@computed_fieldでデコレートされたプライベートプロパティは、デフォルトでrepr=Falseです。

from functools import cached_property

from pydantic import BaseModel, computed_field

class Model(BaseModel):
    foo: int

    @computed_field
    @cached_property
    def _private_cached_property(self) -> int:
        return -self.foo

    @computed_field
    @property
    def _private_property(self) -> int:
        return -self.foo

m = Model(foo=1)
print(repr(m))
#> M(foo=1)

Parameters:

Name Type Description Default
func PropertyT | None

ラップする関数。

None
alias str | None

この計算フィールドをシリアライズするときに使用するエイリアス。by_alias=Trueの場合にのみ使用されます。

None
alias_priority int | None

別名の優先度。これは、別名ジェネレータを使用するかどうかに影響します。

None
title str | None

この計算フィールドをJSONスキーマに含めるときに使用するタイトル

None
field_title_generator Callable[[str, ComputedFieldInfo], str] | None

フィールド名を受け取り、そのタイトルを返す呼び出し可能オブジェクト。

None
description str | None

この計算フィールドをJSONスキーマに含めるときに使用する説明。デフォルトは関数のdocstringです。

None
deprecated Deprecated | str | bool | None

非推奨メッセージ(またはwarnings.deprecatedまたはtyping_extensions.deprecatedバックポートのインスタンス)。フィールドにアクセスするときに発行されます。またはブール値。プロパティがdeprecatedデコレータでデコレートされている場合、これは自動的に設定されます。

None
examples list[Any] | None

この計算フィールドをJSONスキーマに含める場合に使用する値の例

None
json_schema_extra JsonDict | Callable[[JsonDict], None] | None

追加のJSONスキーマ・プロパティーを提供するためのdictまたはcallable。

None
repr bool | None

この計算済みフィールドをモデルreprに含めるかどうか。デフォルトは、プライベートプロパティの場合はFalseで、パブリックプロパティの場合はTrueです。

None
return_type Any

JSONへのシリアライズ時に期待されるシリアライズロジックのオプションの戻り値。これが含まれている場合は正しくなければなりません。含まれていない場合はTypeErrorが発生します。戻り値の型が含まれていない場合は、任意のオブジェクトを処理するために実行時イントロスペクションを行うAnyが使用されます。

PydanticUndefined

Returns:

Type Description
PropertyT | Callable[[PropertyT], PropertyT]

プロパティのプロキシラッパー。

Source code in pydantic/fields.py
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
def computed_field(
    func: PropertyT | None = None,
    /,
    *,
    alias: str | None = None,
    alias_priority: int | None = None,
    title: str | None = None,
    field_title_generator: typing.Callable[[str, ComputedFieldInfo], str] | None = None,
    description: str | None = None,
    deprecated: Deprecated | str | bool | None = None,
    examples: list[Any] | None = None,
    json_schema_extra: JsonDict | typing.Callable[[JsonDict], None] | None = None,
    repr: bool | None = None,
    return_type: Any = PydanticUndefined,
) -> PropertyT | typing.Callable[[PropertyT], PropertyT]:
    """Usage docs: https://yodai-yodai.github.io/translated/pydantic-docs-ja/concepts/fields#the-computed_field-decorator

    モデルまたはデータクラスをシリアライズするときに`property`と`cached_property`を含めるデコレータ。

    これは、他のフィールドから計算されるフィールドや、計算にコストがかかり、キャッシュする必要があるフィールドに便利です。

    ```py
    from pydantic import BaseModel, computed_field

    class Rectangle(BaseModel):
        width: int
        length: int

        @computed_field
        @property
        def area(self) -> int:
            return self.width * self.length

    print(Rectangle(width=3, length=2).model_dump())
    #> {'width': 3, 'length': 2, 'area': 6}
    ```

    `@property`または`@cached_property`でデコレートされていない関数に適用すると、その関数は自動的に`property`でラップされます。
    これはより簡潔ですが、IDE内のIntelliSenseが失われ、静的型チェッカーが混乱するため、`@property`を明示的に使用することをお勧めします。

    !!! warning "Mypy Warning"
        `@computed_field`の前に`@property`または`@cached_property`を関数に適用しても、mypyは`Decorated property not supported`エラーをスローすることがあります。
        詳細については、[mypy issue #1362](https://github.com/python/mypy/issues/1362)を参照してください。
        このエラーメッセージを回避するには、`@computed_field`行に`#type:ignore[misc]`を追加してください。

        [pyright](https://github.com/microsoft/pyright)はエラーなしで`@computed_field`をサポートしています。

    ```py
    import random

    from pydantic import BaseModel, computed_field

    class Square(BaseModel):
        width: float

        @computed_field
        def area(self) -> float:  # converted to a `property` by `computed_field`
            return round(self.width**2, 2)

        @area.setter
        def area(self, new_area: float) -> None:
            self.width = new_area**0.5

        @computed_field(alias='the magic number', repr=False)
        def random_number(self) -> int:
            return random.randint(0, 1_000)

    square = Square(width=1.3)

    # `random_number` does not appear in representation
    print(repr(square))
    #> Square(width=1.3, area=1.69)

    print(square.random_number)
    #> 3

    square.area = 4

    print(square.model_dump_json(by_alias=True))
    #> {"width":2.0,"area":4.0,"the magic number":3}
    ```

    !!! warning "Overriding with `computed_field`"
        親クラスのフィールドを子クラスの`computed_field`で上書きすることはできません。
        `mypy`は許可されていればこのふるまいは許しませんし、`dataclasses`もこのパターンを許可していません。
        次の例を参照してください。

    ```py
    from pydantic import BaseModel, computed_field

    class Parent(BaseModel):
        a: str

    try:

        class Child(Parent):
            @computed_field
            @property
            def a(self) -> str:
                return 'new a'

    except ValueError as e:
        print(repr(e))
        #> ValueError("you can't override a field with a computed field")
    ```

    `@computed_field`でデコレートされたプライベートプロパティは、デフォルトで`repr=False`です。

    ```py
    from functools import cached_property

    from pydantic import BaseModel, computed_field

    class Model(BaseModel):
        foo: int

        @computed_field
        @cached_property
        def _private_cached_property(self) -> int:
            return -self.foo

        @computed_field
        @property
        def _private_property(self) -> int:
            return -self.foo

    m = Model(foo=1)
    print(repr(m))
    #> M(foo=1)
    ```

    Args:
        func: ラップする関数。
        alias: この計算フィールドをシリアライズするときに使用するエイリアス。`by_alias=True`の場合にのみ使用されます。
        alias_priority: 別名の優先度。これは、別名ジェネレータを使用するかどうかに影響します。
        title: この計算フィールドをJSONスキーマに含めるときに使用するタイトル
        field_title_generator: フィールド名を受け取り、そのタイトルを返す呼び出し可能オブジェクト。
        description: この計算フィールドをJSONスキーマに含めるときに使用する説明。デフォルトは関数のdocstringです。
        deprecated: 非推奨メッセージ(または`warnings.deprecated`または`typing_extensions.deprecated`バックポートのインスタンス)。フィールドにアクセスするときに発行されます。またはブール値。プロパティが`deprecated`デコレータでデコレートされている場合、これは自動的に設定されます。
        examples: この計算フィールドをJSONスキーマに含める場合に使用する値の例
        json_schema_extra: 追加のJSONスキーマ・プロパティーを提供するためのdictまたはcallable。
        repr: この計算済みフィールドをモデルreprに含めるかどうか。デフォルトは、プライベートプロパティの場合は`False`で、パブリックプロパティの場合は`True`です。
        return_type: JSONへのシリアライズ時に期待されるシリアライズロジックのオプションの戻り値。これが含まれている場合は正しくなければなりません。含まれていない場合は`TypeError`が発生します。戻り値の型が含まれていない場合は、任意のオブジェクトを処理するために実行時イントロスペクションを行うAnyが使用されます。

    Returns:
        プロパティのプロキシラッパー。
    """

    def dec(f: Any) -> Any:
        nonlocal description, deprecated, return_type, alias_priority
        unwrapped = _decorators.unwrap_wrapped_function(f)

        if description is None and unwrapped.__doc__:
            description = inspect.cleandoc(unwrapped.__doc__)

        if deprecated is None and hasattr(unwrapped, '__deprecated__'):
            deprecated = unwrapped.__deprecated__

        # if the function isn't already decorated with `@property` (or another descriptor), then we wrap it now
        f = _decorators.ensure_property(f)
        alias_priority = (alias_priority or 2) if alias is not None else None

        if repr is None:
            repr_: bool = not _wrapped_property_is_private(property_=f)
        else:
            repr_ = repr

        dec_info = ComputedFieldInfo(
            f,
            return_type,
            alias,
            alias_priority,
            title,
            field_title_generator,
            description,
            deprecated,
            examples,
            json_schema_extra,
            repr_,
        )
        return _decorators.PydanticDescriptorProxy(f, dec_info)

    if func is None:
        return dec
    else:
        return dec(func)

ComputedFieldInfo dataclass

ComputedFieldInfo(
    wrapped_property: property,
    return_type: Any,
    alias: str | None,
    alias_priority: int | None,
    title: str | None,
    field_title_generator: (
        Callable[[str, ComputedFieldInfo], str] | None
    ),
    description: str | None,
    deprecated: Deprecated | str | bool | None,
    examples: list[Any] | None,
    json_schema_extra: (
        JsonDict | Callable[[JsonDict], None] | None
    ),
    repr: bool,
)

pydantic-coreスキーマを構築する際にアクセスできるように、@computed_fieldからのデータのコンテナ。

Attributes:

Name Type Description
decorator_repr str

デコレータ文字列'@computed_field'を表すクラス変数。

wrapped_property property

ラップされた計算結果フィールド・プロパティ。

return_type Any

計算フィールド・プロパティの戻り値の型。

alias str | None

シリアライズ中に使用されるプロパティのエイリアス。

alias_priority int | None

別名の優先度。これは、別名ジェネレータを使用するかどうかに影響します。

title str | None

シリアライゼーションJSONスキーマに含める計算フィールドのタイトル。

field_title_generator Callable[[str, ComputedFieldInfo], str] | None

フィールド名を受け取り、そのタイトルを返す呼び出し可能オブジェクト。

description str | None

シリアライゼーションJSONスキーマに含める計算フィールドの説明。

deprecated Deprecated | str | bool | None

非推奨メッセージ、warnings.deprecatedまたはtyping_extensions.deprecatedバックポートのインスタンス、またはブール値。Trueの場合、フィールドにアクセスするとデフォルトの非推奨メッセージが出力されます。

examples list[Any] | None

シリアライズJSONスキーマに含める計算結果フィールドの値の例。

json_schema_extra JsonDict | Callable[[JsonDict], None] | None

追加のJSONスキーマ・プロパティーを提供するためのdictまたはcallable。

repr bool

__repr__出力にフィールドを含めるかどうかを示すブール値。

deprecation_message property

deprecation_message: str | None

出力される非推奨メッセージ、または設定されていない場合はNone