跳转到内容

字段

在模型上定义字段。

字段

Field(
    default: ellipsis,
    *,
    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,
    exclude_if: Callable[[Any], 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
Field(
    default: Any,
    *,
    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,
    exclude_if: Callable[[Any], 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: Literal[True],
    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
Field(
    default: _T,
    *,
    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,
    exclude_if: Callable[[Any], 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: Literal[False] = ...,
    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]
) -> _T
Field(
    *,
    default_factory: (
        Callable[[], Any] | Callable[[dict[str, Any]], Any]
    ),
    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,
    exclude_if: Callable[[Any], 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: Literal[True],
    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
Field(
    *,
    default_factory: (
        Callable[[], _T] | Callable[[dict[str, Any]], _T]
    ),
    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,
    exclude_if: Callable[[Any], 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: Literal[False] | 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]
) -> _T
Field(
    *,
    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,
    exclude_if: Callable[[Any], 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
Field(
    default: Any = PydanticUndefined,
    *,
    default_factory: (
        Callable[[], Any]
        | Callable[[dict[str, Any]], 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,
    exclude_if: Callable[[Any], 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

使用文档

字段

为可配置的对象创建字段。

用于提供有关字段的额外信息,无论是用于模型模式还是复杂验证。有些参数仅适用于数字字段(intfloatDecimal),有些仅适用于str

注意
  • 任何 _Unset 对象都将替换为 _DefaultValues 字典中定义的相应值。如果 _Unset 对象的键在 _DefaultValues 字典中找不到,则默认为 None

参数

名称 类型 描述 默认值
默认 Any

如果未设置字段,则为默认值。

PydanticUndefined
default_factory 可调用[[], 任何] | 可调用[[字典[字符串, 任何]], 任何] | 无

一个可生成默认值的可调用对象。可调用对象可以不带参数(在这种情况下按原样调用)或带单个参数,其中包含已验证的数据。

_Unset
alias str | None

通过别名验证或序列化时要用于属性的名称。这通常用于蛇形命名法和驼峰命名法之间的转换。

_Unset
alias_priority int | None

别名的优先级。这会影响是否使用别名生成器。

_Unset
validation_alias 字符串 | 别名路径 | 别名选择 | 无

alias 类似,但仅影响验证,不影响序列化。

_Unset
serialization_alias str | None

alias 类似,但仅影响序列化,不影响验证。

_Unset
title str | None

人类可读的标题。

_Unset
field_title_generator 可调用[[字符串, 字段信息], 字符串] | 无

一个可调用对象,它接受一个字段名称并返回该字段的标题。

_Unset
描述 str | None

人类可读的描述。

_Unset
示例 列表[任何] | 无

此字段的示例值。

_Unset
exclude bool | None

是否将字段从模型序列化中排除。

_Unset
exclude_if 可调用[[任何], 布尔值] | 无

一个可调用对象,根据字段值决定在序列化期间是否排除该字段。

_Unset
discriminator 字符串 | 鉴别器 | 无

用于区分标记联合中的类型的字段名称或鉴别器。

_Unset
已弃用 已弃用 | 字符串 | 布尔值 | 无

一个弃用消息,一个 warnings.deprecated 实例或 typing_extensions.deprecated 后向移植,或一个布尔值。如果为 True,则在访问字段时将发出默认弃用消息。

_Unset
json_schema_extra JsonDict | 可调用[[JsonDict], 无] | 无

一个字典或可调用对象,用于提供额外的 JSON 模式属性。

_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,则对字段应用严格验证。有关详细信息,请参阅严格模式

_Unset
gt SupportsGt | 无

大于。如果设置,值必须大于此值。仅适用于数字。

_Unset
ge SupportsGe | 无

大于或等于。如果设置,值必须大于或等于此值。仅适用于数字。

_Unset
lt SupportsLt | 无

小于。如果设置,值必须小于此值。仅适用于数字。

_Unset
le SupportsLe | 无

小于或等于。如果设置,值必须小于或等于此值。仅适用于数字。

_Unset
multiple_of float | None

值必须是此值的倍数。仅适用于数字。

_Unset
min_length int | None

可迭代对象的最小长度。

_Unset
max_length int | None

可迭代对象的最大长度。

_Unset
pattern str | Pattern[str] | None

字符串模式(正则表达式)。

_Unset
allow_inf_nan bool | None

允许 inf-infnan。仅适用于浮点数和 Decimal 数字。

_Unset
max_digits int | None

字符串允许的最大位数。

_Unset
decimal_places int | None

数字允许的最大小数位数。

_Unset
union_mode 字面量['smart', 'left_to_right']

验证联合时应用的策略。可以是 smart(默认)或 left_to_right。有关详细信息,请参阅联合模式

_Unset
fail_fast bool | None

如果为 True,验证将在第一个错误时停止。如果为 False,将收集所有验证错误。此选项仅适用于可迭代类型(列表、元组、集合和 frozenset)。

_Unset
extra 解包[_EmptyKwargs]

(已弃用)将包含在 JSON 模式中的额外字段。

警告

extra kwargs 已弃用。请改用 json_schema_extra

{}

返回

类型 描述
Any

一个新的FieldInfo。返回注释是 Any,因此 Field 可以在类型注释字段上使用而不会导致类型错误。

源代码在 pydantic/fields.py
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
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
def Field(  # noqa: C901
    default: Any = PydanticUndefined,
    *,
    default_factory: Callable[[], Any] | Callable[[dict[str, Any]], 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,
    exclude_if: Callable[[Any], bool] | None = _Unset,
    discriminator: str | types.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 | re.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:
    """!!! abstract "Usage Documentation"
        [Fields](../concepts/fields.md)

    Create a field for objects that can be configured.

    Used to provide extra information about a field, either for the model schema or complex validation. Some arguments
    apply only to number fields (`int`, `float`, `Decimal`) and some apply only to `str`.

    Note:
        - Any `_Unset` objects will be replaced by the corresponding value defined in the `_DefaultValues` dictionary. If a key for the `_Unset` object is not found in the `_DefaultValues` dictionary, it will default to `None`

    Args:
        default: Default value if the field is not set.
        default_factory: A callable to generate the default value. The callable can either take 0 arguments
            (in which case it is called as is) or a single argument containing the already validated data.
        alias: The name to use for the attribute when validating or serializing by alias.
            This is often used for things like converting between snake and camel case.
        alias_priority: Priority of the alias. This affects whether an alias generator is used.
        validation_alias: Like `alias`, but only affects validation, not serialization.
        serialization_alias: Like `alias`, but only affects serialization, not validation.
        title: Human-readable title.
        field_title_generator: A callable that takes a field name and returns title for it.
        description: Human-readable description.
        examples: Example values for this field.
        exclude: Whether to exclude the field from the model serialization.
        exclude_if: A callable that determines whether to exclude a field during serialization based on its value.
        discriminator: Field name or Discriminator for discriminating the type in a tagged union.
        deprecated: A deprecation message, an instance of `warnings.deprecated` or the `typing_extensions.deprecated` backport,
            or a boolean. If `True`, a default deprecation message will be emitted when accessing the field.
        json_schema_extra: A dict or callable to provide extra JSON schema properties.
        frozen: Whether the field is frozen. If true, attempts to change the value on an instance will raise an error.
        validate_default: If `True`, apply validation to the default value every time you create an instance.
            Otherwise, for performance reasons, the default value of the field is trusted and not validated.
        repr: A boolean indicating whether to include the field in the `__repr__` output.
        init: Whether the field should be included in the constructor of the dataclass.
            (Only applies to dataclasses.)
        init_var: Whether the field should _only_ be included in the constructor of the dataclass.
            (Only applies to dataclasses.)
        kw_only: Whether the field should be a keyword-only argument in the constructor of the dataclass.
            (Only applies to dataclasses.)
        coerce_numbers_to_str: Whether to enable coercion of any `Number` type to `str` (not applicable in `strict` mode).
        strict: If `True`, strict validation is applied to the field.
            See [Strict Mode](../concepts/strict_mode.md) for details.
        gt: Greater than. If set, value must be greater than this. Only applicable to numbers.
        ge: Greater than or equal. If set, value must be greater than or equal to this. Only applicable to numbers.
        lt: Less than. If set, value must be less than this. Only applicable to numbers.
        le: Less than or equal. If set, value must be less than or equal to this. Only applicable to numbers.
        multiple_of: Value must be a multiple of this. Only applicable to numbers.
        min_length: Minimum length for iterables.
        max_length: Maximum length for iterables.
        pattern: Pattern for strings (a regular expression).
        allow_inf_nan: Allow `inf`, `-inf`, `nan`. Only applicable to float and [`Decimal`][decimal.Decimal] numbers.
        max_digits: Maximum number of allow digits for strings.
        decimal_places: Maximum number of decimal places allowed for numbers.
        union_mode: The strategy to apply when validating a union. Can be `smart` (the default), or `left_to_right`.
            See [Union Mode](../concepts/unions.md#union-modes) for details.
        fail_fast: If `True`, validation will stop on the first error. If `False`, all validation errors will be collected.
            This option can be applied only to iterable types (list, tuple, set, and frozenset).
        extra: (Deprecated) Extra fields that will be included in the JSON schema.

            !!! warning Deprecated
                The `extra` kwargs is deprecated. Use `json_schema_extra` instead.

    Returns:
        A new [`FieldInfo`][pydantic.fields.FieldInfo]. The return annotation is `Any` so `Field` can be used on
            type-annotated fields without causing a type error.
    """
    # 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',
            PydanticDeprecatedSince20,
            stacklevel=2,
        )
        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',
            PydanticDeprecatedSince20,
            stacklevel=2,
        )
        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',
            PydanticDeprecatedSince20,
            stacklevel=2,
        )
        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())})',
            PydanticDeprecatedSince20,
            stacklevel=2,
        )
        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',
            PydanticDeprecatedSince20,
            stacklevel=2,
        )

    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,
        exclude_if=exclude_if,
        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])

基类:Representation

此类包含有关字段的信息。

FieldInfo 用于任何字段定义,无论是否明确使用 Field() 函数。

警告

通常不应直接创建 FieldInfo,仅在访问 BaseModel .model_fields 内部时才需要使用它。

属性

名称 类型 描述
注解 类型[任何] | 无

字段的类型注释。

默认 Any

字段的默认值。

default_factory 可调用[[], 任何] | 可调用[[字典[字符串, 任何]], 任何] | 无

一个可生成默认值的可调用对象。可调用对象可以不带参数(在这种情况下按原样调用)或带单个参数,其中包含已验证的数据。

alias str | None

字段的别名。

alias_priority int | None

字段别名的优先级。

validation_alias 字符串 | 别名路径 | 别名选择 | 无

字段的验证别名。

serialization_alias str | None

字段的序列化别名。

title str | None

字段的标题。

field_title_generator 可调用[[字符串, 字段信息], 字符串] | 无

一个可调用对象,它接受一个字段名称并返回该字段的标题。

描述 str | None

字段的描述。

示例 列表[任何] | 无

字段示例列表。

exclude bool | None

是否将字段从模型序列化中排除。

exclude_if 可调用[[任何], 布尔值] | 无

一个可调用对象,根据字段值决定在序列化期间是否排除该字段。

discriminator 字符串 | 鉴别器 | 无

用于区分标记联合中的类型的字段名称或鉴别器。

已弃用 已弃用 | 字符串 | 布尔值 | 无

一个弃用消息,一个 warnings.deprecated 实例或 typing_extensions.deprecated 后向移植,或一个布尔值。如果为 True,则在访问字段时将发出默认弃用消息。

json_schema_extra JsonDict | 可调用[[JsonDict], 无] | 无

一个字典或可调用对象,用于提供额外的 JSON 模式属性。

frozen bool | None

字段是否冻结。

validate_default bool | None

是否验证字段的默认值。

repr bool

是否将字段包含在模型的表示中。

init bool | None

字段是否应包含在数据类的构造函数中。

init_var bool | None

字段是否应 包含在数据类的构造函数中,而不存储。

kw_only bool | None

字段是否应为数据类构造函数中的仅关键字参数。

元数据 列表[任何]

元数据约束列表。

有关预期参数的更多详细信息,请参阅 pydantic.fields.Field 的签名。

源代码在 pydantic/fields.py
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
238
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
def __init__(self, **kwargs: Unpack[_FieldInfoInputs]) -> None:
    """This class should generally not be initialized directly; instead, use the `pydantic.fields.Field` function
    or one of the constructor classmethods.

    See the signature of `pydantic.fields.Field` for more details about the expected arguments.
    """
    self._attributes_set = {k: v for k, v in kwargs.items() if v is not _Unset and k not in self.metadata_lookup}
    kwargs = {k: _DefaultValues.get(k) if v is _Unset else v for k, v in kwargs.items()}  # type: ignore
    self.annotation = kwargs.get('annotation')

    default = kwargs.pop('default', PydanticUndefined)
    if default is Ellipsis:
        self.default = PydanticUndefined
        self._attributes_set.pop('default', None)
    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.exclude_if = kwargs.pop('exclude_if', 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)  # type: ignore

    # Private attributes:
    self._qualifiers: set[Qualifier] = set()
    # Used to rebuild FieldInfo instances:
    self._complete = True
    self._original_annotation: Any = PydanticUndefined
    self._original_assignment: Any = PydanticUndefined

from_field staticmethod

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

使用 Field 函数创建一个新的 FieldInfo 对象。

参数

名称 类型 描述 默认值
默认 Any

字段的默认值。默认为 Undefined。

PydanticUndefined
**kwargs 解包[_FromFieldInfoInputs]

附加参数字典。

{}

抛出

类型 描述
TypeError

如果“annotation”作为关键字参数传递。

返回

类型 描述
FieldInfo

具有给定参数的新 FieldInfo 对象。

示例

您可以通过这种方式创建一个带默认值的字段

import pydantic

class MyModel(pydantic.BaseModel):
    foo: int = pydantic.Field(4)
源代码在 pydantic/fields.py
266
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
@staticmethod
def from_field(default: Any = PydanticUndefined, **kwargs: Unpack[_FromFieldInfoInputs]) -> FieldInfo:
    """Create a new `FieldInfo` object with the `Field` function.

    Args:
        default: The default value for the field. Defaults to Undefined.
        **kwargs: Additional arguments dictionary.

    Raises:
        TypeError: If 'annotation' is passed as a keyword argument.

    Returns:
        A new FieldInfo object with the given parameters.

    Example:
        This is how you can create a field with default value like this:

        ```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],
    *,
    _source: AnnotationSource = ANY
) -> FieldInfo

从裸注释创建 FieldInfo 实例。

此函数在内部用于从裸注释创建 FieldInfo,如下所示

import pydantic

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

我们还考虑了注释可以是 Annotated 的实例,并且 Annotated 中的(非第一个)参数之一是 FieldInfo 的实例的情况,例如

from typing import Annotated

import annotated_types

import pydantic

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

参数

名称 类型 描述 默认值
注解 type[Any]

一个注释对象。

必需

返回

类型 描述
FieldInfo

字段元数据的实例。

源代码在 pydantic/fields.py
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
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
@staticmethod
def from_annotation(annotation: type[Any], *, _source: AnnotationSource = AnnotationSource.ANY) -> FieldInfo:
    """Creates a `FieldInfo` instance from a bare annotation.

    This function is used internally to create a `FieldInfo` from a bare annotation like this:

    ```python
    import pydantic

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

    We also account for the case where the annotation can be an instance of `Annotated` and where
    one of the (not first) arguments in `Annotated` is an instance of `FieldInfo`, e.g.:

    ```python
    from typing import Annotated

    import annotated_types

    import pydantic

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

    Args:
        annotation: An annotation object.

    Returns:
        An instance of the field metadata.
    """
    try:
        inspected_ann = inspect_annotation(
            annotation,
            annotation_source=_source,
            unpack_type_aliases='skip',
        )
    except ForbiddenQualifier as e:
        raise PydanticForbiddenQualifier(e.qualifier, annotation)

    # TODO check for classvar and error?

    # No assigned value, this happens when using a bare `Final` qualifier (also for other
    # qualifiers, but they shouldn't appear here). In this case we infer the type as `Any`
    # because we don't have any assigned value.
    type_expr: Any = Any if inspected_ann.type is UNKNOWN else inspected_ann.type
    final = 'final' in inspected_ann.qualifiers
    metadata = inspected_ann.metadata

    attr_overrides = {'annotation': type_expr}
    if final:
        attr_overrides['frozen'] = True
    field_info = FieldInfo._construct(metadata, **attr_overrides)
    field_info._qualifiers = inspected_ann.qualifiers
    return field_info

from_annotated_attribute staticmethod

from_annotated_attribute(
    annotation: type[Any],
    default: Any,
    *,
    _source: AnnotationSource = ANY
) -> FieldInfo

从带默认值的注释创建 FieldInfo

这用于以下情况

from typing import Annotated

import annotated_types

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

参数

名称 类型 描述 默认值
注解 type[Any]

字段的类型注释。

必需
默认 Any

字段的默认值。

必需

返回

类型 描述
FieldInfo

一个带有传递值的字段对象。

源代码在 pydantic/fields.py
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
412
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
@staticmethod
def from_annotated_attribute(
    annotation: type[Any], default: Any, *, _source: AnnotationSource = AnnotationSource.ANY
) -> FieldInfo:
    """Create `FieldInfo` from an annotation with a default value.

    This is used in cases like the following:

    ```python
    from typing import Annotated

    import annotated_types

    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: The type annotation of the field.
        default: The default value of the field.

    Returns:
        A field object with the passed values.
    """
    if annotation is not MISSING and 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',
        )

    try:
        inspected_ann = inspect_annotation(
            annotation,
            annotation_source=_source,
            unpack_type_aliases='skip',
        )
    except ForbiddenQualifier as e:
        raise PydanticForbiddenQualifier(e.qualifier, annotation)

    # TODO check for classvar and error?

    # TODO infer from the default, this can be done in v3 once we treat final fields with
    # a default as proper fields and not class variables:
    type_expr: Any = Any if inspected_ann.type is UNKNOWN else inspected_ann.type
    final = 'final' in inspected_ann.qualifiers
    metadata = inspected_ann.metadata

    # HACK 1: the order in which the metadata is merged is inconsistent; we need to prepend
    # metadata from the assignment at the beginning of the metadata. Changing this is only
    # possible in v3 (at least). See https://github.com/pydantic/pydantic/issues/10507
    prepend_metadata: list[Any] | None = None
    attr_overrides = {'annotation': type_expr}
    if final:
        attr_overrides['frozen'] = True

    # HACK 2: FastAPI is subclassing `FieldInfo` and historically expected the actual
    # instance's type to be preserved when constructing new models with its subclasses as assignments.
    # This code is never reached by Pydantic itself, and in an ideal world this shouldn't be necessary.
    if not metadata and isinstance(default, FieldInfo) and type(default) is not FieldInfo:
        field_info = default._copy()
        field_info._attributes_set.update(attr_overrides)
        for k, v in attr_overrides.items():
            setattr(field_info, k, v)
        return field_info

    if isinstance(default, FieldInfo):
        default_copy = default._copy()  # Copy unnecessary when we remove HACK 1.
        prepend_metadata = default_copy.metadata
        default_copy.metadata = []
        metadata = metadata + [default_copy]
    elif isinstance(default, dataclasses.Field):
        from_field = FieldInfo._from_dataclass_field(default)
        prepend_metadata = from_field.metadata  # Unnecessary when we remove HACK 1.
        from_field.metadata = []
        metadata = metadata + [from_field]
        if 'init_var' in inspected_ann.qualifiers:
            attr_overrides['init_var'] = True
        if (init := getattr(default, 'init', None)) is not None:
            attr_overrides['init'] = init
        if (kw_only := getattr(default, 'kw_only', None)) is not None:
            attr_overrides['kw_only'] = kw_only
    else:
        # `default` is the actual default value
        attr_overrides['default'] = default

    field_info = FieldInfo._construct(
        prepend_metadata + metadata if prepend_metadata is not None else metadata, **attr_overrides
    )
    field_info._qualifiers = inspected_ann.qualifiers
    return field_info

merge_field_infos staticmethod

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

合并 FieldInfo 实例,仅保留显式设置的属性。

后来的 FieldInfo 实例会覆盖早期的实例。

返回

名称 类型 描述
FieldInfo FieldInfo

一个合并的 FieldInfo 实例。

源代码在 pydantic/fields.py
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
@staticmethod
@typing_extensions.deprecated(
    "The 'merge_field_infos()' method is deprecated and will be removed in a future version. "
    'If you relied on this method, please open an issue in the Pydantic issue tracker.',
    category=None,
)
def merge_field_infos(*field_infos: FieldInfo, **overrides: Any) -> FieldInfo:
    """Merge `FieldInfo` instances keeping only explicitly set attributes.

    Later `FieldInfo` instances override earlier ones.

    Returns:
        FieldInfo: A merged FieldInfo instance.
    """
    if len(field_infos) == 1:
        # No merging necessary, but we still need to make a copy and apply the overrides
        field_info = field_infos[0]._copy()
        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 existing_json_schema_extra is None:
                merged_field_info_kwargs['json_schema_extra'] = json_schema_extra
            if isinstance(existing_json_schema_extra, dict):
                if isinstance(json_schema_extra, dict):
                    merged_field_info_kwargs['json_schema_extra'] = {
                        **existing_json_schema_extra,
                        **json_schema_extra,
                    }
                if callable(json_schema_extra):
                    warn(
                        'Composing `dict` and `callable` type `json_schema_extra` is not supported.'
                        'The `callable` type is being ignored.'
                        "If you'd like support for this behavior, please open an issue on pydantic.",
                        PydanticJsonSchemaWarning,
                    )
            elif callable(json_schema_extra):
                # 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

default_factory_takes_validated_data property

default_factory_takes_validated_data: bool | None

提供的默认工厂可调用对象是否具有已验证的数据参数。

如果未设置默认工厂,则返回 None

get_default

get_default(
    *,
    call_default_factory: Literal[True],
    validated_data: dict[str, Any] | None = None
) -> Any
get_default(
    *, call_default_factory: Literal[False] = ...
) -> Any
get_default(
    *,
    call_default_factory: bool = False,
    validated_data: dict[str, Any] | None = None
) -> Any

获取默认值。

我们提供了一个选项,用于是否调用 default_factory(如果存在),因为调用它可能会导致我们想要避免的副作用。但是,有些时候确实应该调用它(即通过 model_construct 实例化模型时)。

参数

名称 类型 描述 默认值
call_default_factory bool

是否调用默认工厂。

False
validated_data dict[str, Any] | None

要传递给默认工厂的已验证数据。

None

返回

类型 描述
Any

默认值,如果请求则调用默认工厂,如果未设置则为 None

源代码在 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
def get_default(self, *, call_default_factory: bool = False, validated_data: dict[str, Any] | None = None) -> Any:
    """Get the default value.

    We expose an option for whether to call the default_factory (if present), as calling it may
    result in side effects that we want to avoid. However, there are times when it really should
    be called (namely, when instantiating a model via `model_construct`).

    Args:
        call_default_factory: Whether to call the default factory or not.
        validated_data: The already validated data to be passed to the default factory.

    Returns:
        The default value, calling the default factory if requested or `None` if not set.
    """
    if self.default_factory is None:
        return _utils.smart_deepcopy(self.default)
    elif call_default_factory:
        if self.default_factory_takes_validated_data:
            fac = cast('Callable[[dict[str, Any]], Any]', self.default_factory)
            if validated_data is None:
                raise ValueError(
                    "The default factory requires the 'validated_data' argument, which was not provided when calling 'get_default'."
                )
            return fac(validated_data)
        else:
            fac = cast('Callable[[], Any]', self.default_factory)
            return fac()
    else:
        return None

is_required

is_required() -> bool

检查字段是否必填(即,没有默认值或工厂)。

返回

类型 描述
bool

如果字段是必填的,则为 True,否则为 False

源代码在 pydantic/fields.py
707
708
709
710
711
712
713
def is_required(self) -> bool:
    """Check if the field is required (i.e., does not have a default value or factory).

    Returns:
        `True` if the field is required, `False` otherwise.
    """
    return self.default is PydanticUndefined and self.default_factory is None

rebuild_annotation

rebuild_annotation() -> Any

尝试重建原始注释以用于函数签名。

如果存在元数据,它会使用 Annotated 将其添加到原始注释。否则,它会按原样返回原始注释。

请注意,由于元数据已扁平化,原始注释可能无法完全按原始提供的方式重新构造,例如,如果原始类型具有无法识别的注释,或使用对 pydantic.Field 的调用进行了注释。

返回

类型 描述
Any

重建的注释。

源代码在 pydantic/fields.py
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
def rebuild_annotation(self) -> Any:
    """Attempts to rebuild the original annotation for use in function signatures.

    If metadata is present, it adds it to the original annotation using
    `Annotated`. Otherwise, it returns the original annotation as-is.

    Note that because the metadata has been flattened, the original annotation
    may not be reconstructed exactly as originally provided, e.g. if the original
    type had unrecognized annotations, or was annotated with a call to `pydantic.Field`.

    Returns:
        The rebuilt annotation.
    """
    if not self.metadata:
        return self.annotation
    else:
        # Annotated arguments must be a tuple
        return Annotated[(self.annotation, *self.metadata)]  # type: ignore

apply_typevars_map

apply_typevars_map(
    typevars_map: Mapping[TypeVar, Any] | None,
    globalns: GlobalsNamespace | None = None,
    localns: MappingNamespace | None = None,
) -> None

typevars_map 应用于注释。

此方法在分析参数化泛型类型时用于将类型变量替换为其具体类型。

此方法将 typevars_map 应用于原位注释。

参数

名称 类型 描述 默认值
typevars_map 映射[TypeVar, 任何] | 无

将类型变量映射到其具体类型的字典。

必需
globalns GlobalsNamespace | 无

在类型注释评估期间使用的全局命名空间。

None
localns MappingNamespace | None

在类型注释评估期间使用的局部命名空间。

None
另请参阅

pydantic._internal._generics.replace_types 用于将类型变量替换为其具体类型。

源代码在 pydantic/fields.py
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
def apply_typevars_map(
    self,
    typevars_map: Mapping[TypeVar, Any] | None,
    globalns: GlobalsNamespace | None = None,
    localns: MappingNamespace | None = None,
) -> None:
    """Apply a `typevars_map` to the annotation.

    This method is used when analyzing parametrized generic types to replace typevars with their concrete types.

    This method applies the `typevars_map` to the annotation in place.

    Args:
        typevars_map: A dictionary mapping type variables to their concrete types.
        globalns: The globals namespace to use during type annotation evaluation.
        localns: The locals namespace to use during type annotation evaluation.

    See Also:
        pydantic._internal._generics.replace_types is used for replacing the typevars with
            their concrete types.
    """
    annotation = _generics.replace_types(self.annotation, typevars_map)
    annotation, evaluated = _typing_extra.try_eval_type(annotation, globalns, localns)
    self.annotation = annotation
    if not evaluated:
        self._complete = False
        self._original_annotation = self.annotation

PrivateAttr

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

使用文档

私有模型属性

表示属性用于私有用途,不在正常验证/序列化期间处理。

私有属性不受 Pydantic 验证,因此您需要确保以类型安全的方式使用它们。

私有属性存储在模型上的 __private_attributes__ 中。

参数

名称 类型 描述 默认值
默认 Any

属性的默认值。默认为 Undefined。

PydanticUndefined
default_factory 可调用[[], 任何] | 无

当需要此属性的默认值时将调用的可调用对象。如果 defaultdefault_factory 都已设置,则会引发错误。

None
init 字面量[假]

属性是否应包含在数据类的构造函数中。始终为 False

False

返回

类型 描述
Any

ModelPrivateAttr 类的实例。

抛出

类型 描述
ValueError

如果 defaultdefault_factory 都已设置。

源代码在 pydantic/fields.py
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
def PrivateAttr(
    default: Any = PydanticUndefined,
    *,
    default_factory: Callable[[], Any] | None = None,
    init: Literal[False] = False,
) -> Any:
    """!!! abstract "Usage Documentation"
        [Private Model Attributes](../concepts/models.md#private-model-attributes)

    Indicates that an attribute is intended for private use and not handled during normal validation/serialization.

    Private attributes are not validated by Pydantic, so it's up to you to ensure they are used in a type-safe manner.

    Private attributes are stored in `__private_attributes__` on the model.

    Args:
        default: The attribute's default value. Defaults to Undefined.
        default_factory: Callable that will be
            called when a default value is needed for this attribute.
            If both `default` and `default_factory` are set, an error will be raised.
        init: Whether the attribute should be included in the constructor of the dataclass. Always `False`.

    Returns:
        An instance of [`ModelPrivateAttr`][pydantic.fields.ModelPrivateAttr] class.

    Raises:
        ValueError: If both `default` and `default_factory` are set.
    """
    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
)

基类:Representation

类模型中私有属性的描述符。

警告

通常不应直接创建 ModelPrivateAttr 实例,而应使用 pydantic.fields.PrivateAttr。(这类似于 FieldInfoField。)

属性

名称 类型 描述
默认

如果未提供,则为属性的默认值。

default_factory

一个可调用函数,如果未提供,则生成属性的默认值。

源代码在 pydantic/fields.py
1348
1349
1350
1351
1352
1353
def __init__(self, default: Any = PydanticUndefined, *, default_factory: Callable[[], Any] | None = None) -> None:
    if default is Ellipsis:
        self.default = PydanticUndefined
    else:
        self.default = default
    self.default_factory = default_factory

get_default

get_default() -> Any

检索对象的默认值。

如果 self.default_factoryNone,则该方法将返回 self.default 对象的深层副本。

如果 self.default_factory 不为 None,它将调用 self.default_factory 并返回返回的值。

返回

类型 描述
Any

对象的默认值。

源代码在 pydantic/fields.py
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
def get_default(self) -> Any:
    """Retrieve the default value of the object.

    If `self.default_factory` is `None`, the method will return a deep copy of the `self.default` object.

    If `self.default_factory` is not `None`, it will call `self.default_factory` and return the value returned.

    Returns:
        The default value of the object.
    """
    return _utils.smart_deepcopy(self.default) if self.default_factory is None else self.default_factory()

computed_field

computed_field(func: PropertyT) -> PropertyT
computed_field(
    *,
    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 = True,
    return_type: Any = PydanticUndefined
) -> Callable[[PropertyT], PropertyT]
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]

用于在序列化模型或数据类时包含 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 中的智能感知,并混淆静态类型检查器,因此建议显式使用 @property

Mypy 警告

即使在 @computed_field 之前将 @property@cached_property 应用于您的函数,mypy 仍可能抛出 Decorated property not supported 错误。有关详细信息,请参阅 mypy issue #1362。要避免此错误消息,请在 @computed_field 行添加 # type: ignore[prop-decorator]

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}

使用 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 TypeError as e:
    print(e)
    '''
    Field 'a' of class 'Child' overrides symbol of same name in a parent class. This override with a computed_field is incompatible.
    '''

@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))
#> Model(foo=1)

参数

名称 类型 描述 默认值
func PropertyT | 无

要包装的函数。

None
alias str | None

序列化此计算字段时要使用的别名,仅在 by_alias=True 时使用

None
alias_priority int | None

别名的优先级。这会影响是否使用别名生成器

None
title str | None

将此计算字段包含在 JSON 模式中时使用的标题

None
field_title_generator 可调用[[字符串, ComputedFieldInfo], 字符串] | 无

一个可调用对象,它接受一个字段名称并返回该字段的标题。

None
描述 str | None

将此计算字段包含在 JSON 模式中时使用的描述,默认为函数的文档字符串

None
已弃用 已弃用 | 字符串 | 布尔值 | 无

一个弃用消息(或 warnings.deprecated 的实例或 typing_extensions.deprecated 后向移植)。在访问字段时发出。或一个布尔值。如果属性用 deprecated 装饰器装饰,这将自动设置。

None
示例 列表[任何] | 无

将此计算字段包含在 JSON 模式中时使用的示例值

None
json_schema_extra JsonDict | 可调用[[JsonDict], 无] | 无

一个字典或可调用对象,用于提供额外的 JSON 模式属性。

None
repr bool | None

是否将此计算字段包含在模型 repr 中。私有属性默认为 False,公共属性默认为 True

None
return_type Any

序列化为 JSON 时序列化逻辑预期的可选返回值,如果包含此值则必须正确,否则会引发 TypeError。如果不包含返回类型,则使用 Any,它会进行运行时自省以处理任意对象。

PydanticUndefined

返回

类型 描述
PropertyT | 可调用[[PropertyT], PropertyT]

属性的代理包装器。

源代码在 pydantic/fields.py
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
def 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]:
    """!!! abstract "Usage Documentation"
        [The `computed_field` decorator](../concepts/fields.md#the-computed_field-decorator)

    Decorator to include `property` and `cached_property` when serializing models or dataclasses.

    This is useful for fields that are computed from other fields, or for fields that are expensive to compute and should be cached.

    ```python
    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}
    ```

    If applied to functions not yet decorated with `@property` or `@cached_property`, the function is
    automatically wrapped with `property`. Although this is more concise, you will lose IntelliSense in your IDE,
    and confuse static type checkers, thus explicit use of `@property` is recommended.

    !!! warning "Mypy Warning"
        Even with the `@property` or `@cached_property` applied to your function before `@computed_field`,
        mypy may throw a `Decorated property not supported` error.
        See [mypy issue #1362](https://github.com/python/mypy/issues/1362), for more information.
        To avoid this error message, add `# type: ignore[prop-decorator]` to the `@computed_field` line.

        [pyright](https://github.com/microsoft/pyright) supports `@computed_field` without error.

    ```python
    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`"
        You can't override a field from a parent class with a `computed_field` in the child class.
        `mypy` complains about this behavior if allowed, and `dataclasses` doesn't allow this pattern either.
        See the example below:

    ```python
    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 TypeError as e:
        print(e)
        '''
        Field 'a' of class 'Child' overrides symbol of same name in a parent class. This override with a computed_field is incompatible.
        '''
    ```

    Private properties decorated with `@computed_field` have `repr=False` by default.

    ```python
    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))
    #> Model(foo=1)
    ```

    Args:
        func: the function to wrap.
        alias: alias to use when serializing this computed field, only used when `by_alias=True`
        alias_priority: priority of the alias. This affects whether an alias generator is used
        title: Title to use when including this computed field in JSON Schema
        field_title_generator: A callable that takes a field name and returns title for it.
        description: Description to use when including this computed field in JSON Schema, defaults to the function's
            docstring
        deprecated: A deprecation message (or an instance of `warnings.deprecated` or the `typing_extensions.deprecated` backport).
            to be emitted when accessing the field. Or a boolean. This will automatically be set if the property is decorated with the
            `deprecated` decorator.
        examples: Example values to use when including this computed field in JSON Schema
        json_schema_extra: A dict or callable to provide extra JSON schema properties.
        repr: whether to include this computed field in model repr.
            Default is `False` for private properties and `True` for public properties.
        return_type: optional return for serialization logic to expect when serializing to JSON, if included
            this must be correct, otherwise a `TypeError` is raised.
            If you don't include a return type Any is used, which does runtime introspection to handle arbitrary
            objects.

    Returns:
        A proxy wrapper for the property.
    """

    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 数据类

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,
)

@computed_field 数据容器,以便我们可以在构建 pydantic-core 模式时访问它。

属性

名称 类型 描述
decorator_repr str

表示装饰器字符串“@computed_field”的类变量。

wrapped_property 属性

包装的计算字段属性。

return_type Any

计算字段属性返回值的类型。

alias str | None

序列化期间要使用的属性别名。

alias_priority int | None

别名的优先级。这会影响是否使用别名生成器。

title str | None

要包含在序列化 JSON 模式中的计算字段的标题。

field_title_generator 可调用[[字符串, ComputedFieldInfo], 字符串] | 无

一个可调用对象,它接受一个字段名称并返回该字段的标题。

描述 str | None

要包含在序列化 JSON 模式中的计算字段的描述。

已弃用 已弃用 | 字符串 | 布尔值 | 无

一个弃用消息,一个 warnings.deprecated 实例或 typing_extensions.deprecated 后向移植,或一个布尔值。如果为 True,则在访问字段时将发出默认弃用消息。

示例 列表[任何] | 无

要包含在序列化 JSON 模式中的计算字段的示例值。

json_schema_extra JsonDict | 可调用[[JsonDict], 无] | 无

一个字典或可调用对象,用于提供额外的 JSON 模式属性。

repr bool

一个布尔值,指示是否将字段包含在 repr 输出中。

deprecation_message property

deprecation_message: str | None

要发出的弃用消息,如果未设置则为 None