Unofficial research mirror of the Pydantic documentation (MIT licence) for an academic study. Some details differ from the official documentation, so do not rely on this site for real projects. Official docs: docs.pydantic.dev. About this study.
Skip to content

Fields

Defining fields on models.

Field

Field(
    default: EllipsisType,
    *,
    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

Usage Documentation

Fields

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 default value of the FieldInfo constructor.

Parameters:

Name Type Description Default
default Any

Default value if the field is not set.

PydanticUndefined
default_factory Callable[[], Any] | Callable[[dict[str, Any]], Any] | None

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.

_Unset
alias str | None

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.

_Unset
alias_priority int | None

Priority of the alias. This affects whether an alias generator is used.

_Unset
validation_alias str | AliasPath | AliasChoices | None

Like alias, but only affects validation, not serialization.

_Unset
serialization_alias str | None

Like alias, but only affects serialization, not validation.

_Unset
title str | None

Human-readable title.

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

A callable that takes a field's name and info and returns title for it.

_Unset
description str | None

Human-readable description.

_Unset
examples list[Any] | None

Example values for this field.

_Unset
exclude bool | None

Whether to exclude the field from the model serialization.

_Unset
exclude_if Callable[[Any], bool] | None

A callable that determines whether to exclude a field during serialization based on its value.

_Unset
discriminator str | Discriminator | None

Field name or Discriminator for discriminating the type in a tagged union.

_Unset
deprecated Deprecated | str | bool | None

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.

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

A dict or callable to provide extra JSON schema properties.

_Unset
frozen bool | None

Whether the field is frozen. If true, attempts to change the value on an instance will raise an error.

_Unset
validate_default bool | None

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.

_Unset
repr bool

A boolean indicating whether to include the field in the __repr__ output.

_Unset
init bool | None

Whether the field should be included in the constructor of the dataclass. (Only applies to dataclasses.)

_Unset
init_var bool | None

Whether the field should only be included in the constructor of the dataclass. (Only applies to dataclasses.)

_Unset
kw_only bool | None

Whether the field should be a keyword-only argument in the constructor of the dataclass. (Only applies to dataclasses.)

_Unset
coerce_numbers_to_str bool | None

Whether to enable coercion of any Number type to str (not applicable in strict mode).

_Unset
strict bool | None

If True, strict validation is applied to the field. See Strict Mode for details.

_Unset
gt SupportsGt | None

Greater than. If set, value must be greater than this. Only applicable to numbers.

_Unset
ge SupportsGe | None

Greater than or equal. If set, value must be greater than or equal to this. Only applicable to numbers.

_Unset
lt SupportsLt | None

Less than. If set, value must be less than this. Only applicable to numbers.

_Unset
le SupportsLe | None

Less than or equal. If set, value must be less than or equal to this. Only applicable to numbers.

_Unset
multiple_of float | None

Value must be a multiple of this. Only applicable to numbers.

_Unset
min_length int | None

Minimum length for iterables.

_Unset
max_length int | None

Maximum length for iterables.

_Unset
pattern str | Pattern[str] | None

Pattern for strings (a regular expression).

_Unset
allow_inf_nan bool | None

Allow inf, -inf, nan. Only applicable to float and Decimal numbers.

_Unset
max_digits int | None

Maximum number of allowed digits for Decimal numbers.

_Unset
decimal_places int | None

Maximum number of decimal places allowed for numbers.

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

The strategy to apply when validating a union. Can be smart (the default), or left_to_right. See Union Mode for details.

_Unset
fail_fast bool | None

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

_Unset
extra Unpack[_EmptyKwargs]

(Deprecated) Extra fields that will be included in the JSON schema.

Warning

The extra kwargs is deprecated. Use json_schema_extra instead.

{}

Returns:

Type Description
Any

A new FieldInfo. The return annotation is Any so Field can be used on type-annotated fields without causing a type error.

Source code in pydantic/fields.py
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
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
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
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 default value of the `FieldInfo` constructor.

    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's name and info 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 allowed digits for [`Decimal`][decimal.Decimal] numbers.
        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(
    *,
    annotation: TypeForm[Any] | None = _Unset,
    default: Any = _Unset,
    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,
    coerce_numbers_to_str: bool | None = _Unset,
    strict: bool | None = _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 = _Unset,
    max_length: int | None = _Unset,
    allow_inf_nan: bool | None = _Unset,
    max_digits: int | None = _Unset,
    decimal_places: int | None = _Unset,
    union_mode: (
        Literal["smart", "left_to_right"] | None
    ) = _Unset,
    fail_fast: bool | None = _Unset,
    **kwargs: Any
)

Bases: Representation

This class holds information about a field.

FieldInfo is used for any field definition regardless of whether the Field() function is explicitly used.

Warning

The FieldInfo class is meant to expose information about a field in a Pydantic model or dataclass. FieldInfo instances shouldn't be instantiated directly, nor mutated.

If you need to derive a new model from another one and are willing to alter FieldInfo instances, refer to this dynamic model example.

Attributes:

Name Type Description
annotation TypeForm[Any] | None

The type annotation of the field.

default Any

The default value of the field.

default_factory Callable[[], Any] | Callable[[dict[str, Any]], Any] | None

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 str | None

The alias name of the field.

alias_priority int | None

The priority of the field's alias.

validation_alias str | AliasPath | AliasChoices | None

The validation alias of the field.

serialization_alias str | None

The serialization alias of the field.

title str | None

The title of the field.

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

A callable that takes a field's name and info and returns title for it.

description str | None

The description of the field.

examples list[Any] | None

List of examples of the field.

exclude bool | None

Whether to exclude the field from the model serialization.

exclude_if Callable[[Any], bool] | None

A callable that determines whether to exclude a field during serialization based on its value.

discriminator str | Discriminator | None

Field name or Discriminator for discriminating the type in a tagged union.

deprecated Deprecated | str | bool | None

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 JsonDict | Callable[[JsonDict], None] | None

A dict or callable to provide extra JSON schema properties.

frozen bool | None

Whether the field is frozen.

validate_default bool | None

Whether to validate the default value of the field.

repr bool

Whether to include the field in representation of the model.

init bool | None

Whether the field should be included in the constructor of the dataclass.

init_var bool | None

Whether the field should only be included in the constructor of the dataclass, and not stored.

kw_only bool | None

Whether the field should be a keyword-only argument in the constructor of the dataclass.

metadata list[Any]

The metadata list. Contains all the data that isn't expressed as direct FieldInfo attributes, including:

  • Type-specific constraints, such as gt or min_length (these are converted to metadata classes such as annotated_types.Gt).
  • Any other arbitrary object used within Annotated metadata (e.g. custom types handlers or any object not recognized by Pydantic).

See the signature of pydantic.fields.Field for more details about the expected arguments. Unknown keyword arguments are accepted (and ignored) for backwards compatibility.

Source code in pydantic/fields.py
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
265
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
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
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
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
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
448
449
450
451
452
453
454
455
456
457
458
459
460
def __init__(
    self,
    *,
    annotation: TypeForm[Any] | None = _Unset,
    default: Any = _Unset,
    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,
    # The following arguments are converted to metadata (see `_collect_metadata()`), in the order `Field()` forwards them:
    pattern: str | re.Pattern[str] | None = _Unset,
    coerce_numbers_to_str: bool | None = _Unset,
    strict: 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,
    min_length: int | None = _Unset,
    max_length: int | None = _Unset,
    allow_inf_nan: bool | None = _Unset,
    max_digits: int | None = _Unset,
    decimal_places: int | None = _Unset,
    union_mode: Literal['smart', 'left_to_right'] | None = _Unset,
    fail_fast: bool | None = _Unset,
    **kwargs: Any,
) -> 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.
    Unknown keyword arguments are accepted (and ignored) for backwards compatibility.
    """
    # Tracking the explicitly set attributes is necessary to correctly merge `Field()` functions
    # (e.g. with `Annotated[int, Field(alias='a'), Field(alias=None)]`, even though `None` is the default value,
    # we need to track that `alias=None` was explicitly set):
    self._attributes_set = attributes_set = {}

    if annotation is _Unset:
        annotation = None
    else:
        attributes_set['annotation'] = annotation
    self.annotation = annotation

    if default is _Unset or default is Ellipsis:
        default = PydanticUndefined
    else:
        attributes_set['default'] = default
    self.default = default

    if default_factory is _Unset:
        default_factory = None
    else:
        attributes_set['default_factory'] = default_factory
    self.default_factory = default_factory

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

    if alias is _Unset:
        alias = None
    else:
        attributes_set['alias'] = alias
    self.alias = alias

    if alias_priority is _Unset:
        alias_priority = None
    else:
        attributes_set['alias_priority'] = alias_priority

    if validation_alias is _Unset:
        validation_alias = None
    else:
        attributes_set['validation_alias'] = validation_alias
    self.validation_alias = validation_alias

    if serialization_alias is _Unset:
        serialization_alias = None
    else:
        attributes_set['serialization_alias'] = serialization_alias
    self.serialization_alias = serialization_alias

    alias_is_set = alias is not None or validation_alias is not None or serialization_alias is not None
    self.alias_priority = (alias_priority or 2) if alias_is_set else None

    if title is _Unset:
        title = None
    else:
        attributes_set['title'] = title
    self.title = title

    if field_title_generator is _Unset:
        field_title_generator = None
    else:
        attributes_set['field_title_generator'] = field_title_generator
    self.field_title_generator = field_title_generator

    if description is _Unset:
        description = None
    else:
        attributes_set['description'] = description
    self.description = description

    if examples is _Unset:
        examples = None
    else:
        attributes_set['examples'] = examples
    self.examples = examples

    if exclude is _Unset:
        exclude = None
    else:
        attributes_set['exclude'] = exclude
    self.exclude = exclude

    if exclude_if is _Unset:
        exclude_if = None
    else:
        attributes_set['exclude_if'] = exclude_if
    self.exclude_if = exclude_if

    if discriminator is _Unset:
        discriminator = None
    else:
        attributes_set['discriminator'] = discriminator
    self.discriminator = discriminator

    if deprecated is _Unset:
        # For compatibility with FastAPI<=0.110.0, we preserve the existing value if it is not overridden
        deprecated = getattr(self, 'deprecated', None)
    else:
        attributes_set['deprecated'] = deprecated
    self.deprecated = deprecated

    if repr is _Unset:
        repr = True
    else:
        attributes_set['repr'] = repr
    self.repr = repr

    if json_schema_extra is _Unset:
        json_schema_extra = None
    else:
        attributes_set['json_schema_extra'] = json_schema_extra
    self.json_schema_extra = json_schema_extra

    if validate_default is _Unset:
        validate_default = None
    else:
        attributes_set['validate_default'] = validate_default
    self.validate_default = validate_default

    if frozen is _Unset:
        frozen = None
    else:
        attributes_set['frozen'] = frozen
    self.frozen = frozen

    # currently only used on dataclasses
    if init is _Unset:
        init = None
    else:
        attributes_set['init'] = init
    self.init = init

    if init_var is _Unset:
        init_var = None
    else:
        attributes_set['init_var'] = init_var
    self.init_var = init_var

    if kw_only is _Unset:
        kw_only = None
    else:
        attributes_set['kw_only'] = kw_only
    self.kw_only = kw_only

    # (in the order `Field()` forwards them, which determines the order of the metadata)
    metadata_kwargs: dict[str, Any] = {}
    if pattern is not _Unset:
        metadata_kwargs['pattern'] = pattern
    if coerce_numbers_to_str is not _Unset:
        metadata_kwargs['coerce_numbers_to_str'] = coerce_numbers_to_str
    if strict is not _Unset:
        metadata_kwargs['strict'] = strict
    if gt is not _Unset:
        metadata_kwargs['gt'] = gt
    if ge is not _Unset:
        metadata_kwargs['ge'] = ge
    if lt is not _Unset:
        metadata_kwargs['lt'] = lt
    if le is not _Unset:
        metadata_kwargs['le'] = le
    if multiple_of is not _Unset:
        metadata_kwargs['multiple_of'] = multiple_of
    if min_length is not _Unset:
        metadata_kwargs['min_length'] = min_length
    if max_length is not _Unset:
        metadata_kwargs['max_length'] = max_length
    if allow_inf_nan is not _Unset:
        metadata_kwargs['allow_inf_nan'] = allow_inf_nan
    if max_digits is not _Unset:
        metadata_kwargs['max_digits'] = max_digits
    if decimal_places is not _Unset:
        metadata_kwargs['decimal_places'] = decimal_places
    if union_mode is not _Unset:
        metadata_kwargs['union_mode'] = union_mode
    if fail_fast is not _Unset:
        metadata_kwargs['fail_fast'] = fail_fast
    self.metadata = self._collect_metadata(metadata_kwargs) if metadata_kwargs else []

    if kwargs:
        # Unknown keyword arguments (kept for backwards compatibility):
        attributes_set.update({key: value for key, value in kwargs.items() if value is not _Unset})

    # 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
    # Used to track whether the `FieldInfo` instance represents the data about a field (and is exposed in `model_fields`/`__pydantic_fields__`),
    # or if it is the result of the `Field()` function being used as metadata in an `Annotated` type/as an assignment
    # (not an ideal pattern, see https://github.com/pydantic/pydantic/issues/11122):
    self._final = False

deprecation_message property

deprecation_message: str | None

The deprecation message to be emitted, or None if not set.

default_factory_takes_validated_data property

default_factory_takes_validated_data: bool | None

Whether the provided default factory callable has a validated data parameter.

Returns None if no default factory is set.

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

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

Parameters:

Name Type Description Default
call_default_factory bool

Whether to call the default factory or not.

False
validated_data dict[str, Any] | None

The already validated data to be passed to the default factory.

None

Returns:

Type Description
Any

The default value, calling the default factory if requested or PydanticUndefined if not set.

Source code in pydantic/fields.py
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
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 `PydanticUndefined` if not set.
    """
    return _fields.resolve_default_value(
        default=self.default,
        default_factory=self.default_factory,
        default_factory_takes_validated_data_argument=self.default_factory_takes_validated_data,
        validated_data=validated_data,
        call_default_factory=call_default_factory,
    )

is_required

is_required() -> bool

Check if the field is required (i.e., does not have a default value or factory).

Returns:

Type Description
bool

True if the field is required, False otherwise.

Source code in pydantic/fields.py
923
924
925
926
927
928
929
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

asdict

asdict() -> _FieldInfoAsDict

Return a dictionary representation of the FieldInfo instance.

The returned value is a dictionary with three items:

  • annotation: The type annotation of the field.
  • metadata: The metadata list.
  • attributes: A mapping of the remaining FieldInfo attributes to their values (e.g. alias, title).
Source code in pydantic/fields.py
978
979
980
981
982
983
984
985
986
987
988
989
990
991
def asdict(self) -> _FieldInfoAsDict:
    """Return a dictionary representation of the `FieldInfo` instance.

    The returned value is a dictionary with three items:

    * `annotation`: The type annotation of the field.
    * `metadata`: The metadata list.
    * `attributes`: A mapping of the remaining `FieldInfo` attributes to their values (e.g. `alias`, `title`).
    """
    return {
        'annotation': self.annotation,
        'metadata': self.metadata,
        'attributes': {attr: getattr(self, attr) for attr in _Attrs},
    }

PrivateAttr

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

Usage Documentation

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.

Parameters:

Name Type Description Default
default Any

The attribute's default value. Defaults to Undefined.

PydanticUndefined
default_factory Callable[[], Any] | Callable[[dict[str, Any]], Any] | None

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 validated data (the model's __dict__) and the already initialized private attributes. If both default and default_factory are set, an error will be raised.

None
init Literal[False]

Whether the attribute should be included in the constructor of the dataclass. Always False.

False

Returns:

Type Description
Any

An instance of ModelPrivateAttr class.

Raises:

Type Description
TypeError

If both default and default_factory are set.

Source code in pydantic/fields.py
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
def PrivateAttr(
    default: Any = PydanticUndefined,
    *,
    default_factory: Callable[[], Any] | Callable[[dict[str, Any]], 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: 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 validated data (the model's
            [`__dict__`][object.__dict__]) and the already initialized private attributes.
            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:
        TypeError: 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]
        | Callable[[dict[str, Any]], Any]
        | None
    ) = None
)

Bases: Representation

A descriptor for private attributes in class models.

Warning

You generally shouldn't be creating ModelPrivateAttr instances directly, instead use the PrivateAttr() function.

Attributes:

Name Type Description
default

The default value of the attribute if not provided.

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 validated data (the model's __dict__) and the already initialized private attributes.

Source code in pydantic/fields.py
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
def __init__(
    self,
    default: Any = PydanticUndefined,
    *,
    default_factory: Callable[[], Any] | Callable[[dict[str, Any]], Any] | None = None,
) -> None:
    if default is Ellipsis:
        self.default = PydanticUndefined
    else:
        self.default = default
    self.default_factory = default_factory
    self._default_factory_takes_validated_data: bool | None = _Unset

__getattr__

__getattr__(item: str) -> Any

This function improves compatibility with custom descriptors by ensuring delegation happens as expected when the default value of a private attribute is a descriptor.

Source code in pydantic/fields.py
1591
1592
1593
1594
1595
1596
1597
1598
def __getattr__(self, item: str) -> Any:
    """This function improves compatibility with custom descriptors by ensuring delegation happens
    as expected when the default value of a private attribute is a descriptor.
    """
    if item in {'__get__', '__set__', '__delete__'}:
        if hasattr(self.default, item):
            return getattr(self.default, item)
    raise AttributeError(f'{type(self).__name__!r} object has no attribute {item!r}')

__set_name__

__set_name__(cls: type[Any], name: str) -> None

Preserve __set_name__ protocol defined in https://peps.python.org/pep-0487.

Source code in pydantic/fields.py
1600
1601
1602
1603
1604
1605
1606
1607
def __set_name__(self, cls: type[Any], name: str) -> None:
    """Preserve `__set_name__` protocol defined in https://peps.python.org/pep-0487."""
    default = self.default
    if default is PydanticUndefined:
        return
    set_name = getattr(default, '__set_name__', None)
    if callable(set_name):
        set_name(cls, name)

default_factory_takes_validated_data property

default_factory_takes_validated_data: bool | None

Whether the provided default factory callable has a validated data parameter.

Returns None if no default factory is set.

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

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

Parameters:

Name Type Description Default
call_default_factory bool

Whether to call the default factory or not.

False
validated_data dict[str, Any] | None

The already validated data to be passed to the default factory.

None

Returns:

Type Description
Any

The default value, calling the default factory if requested or None if not set.

Source code in pydantic/fields.py
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
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.
    """
    return _fields.resolve_default_value(
        default=self.default,
        default_factory=self.default_factory,
        default_factory_takes_validated_data_argument=self.default_factory_takes_validated_data,
        validated_data=validated_data,
        call_default_factory=call_default_factory,
    )

computed_field

computed_field(func: PropertyT) -> PropertyT
computed_field(
    *,
    alias: str | None = None,
    alias_priority: int | None = None,
    exclude_if: Callable[[Any], bool] | 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,
    exclude_if: Callable[[Any], bool] | 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

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.

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.

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, for more information. To avoid this error message, add # type: ignore[prop-decorator] to the @computed_field line.

pyright supports @computed_field without error.

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

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:

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.

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)

Parameters:

Name Type Description Default
func PropertyT | None

the function to wrap.

None
alias str | None

alias to use when serializing this computed field, only used when by_alias=True

None
alias_priority int | None

priority of the alias. This affects whether an alias generator is used

None
exclude_if Callable[[Any], bool] | None

A callable that determines whether to exclude this computed field during serialization based on its value.

None
title str | None

Title to use when including this computed field in JSON Schema

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

A callable that takes a field's name and info and returns title for it.

None
description str | None

Description to use when including this computed field in JSON Schema, defaults to the function's docstring

None
deprecated Deprecated | str | bool | None

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.

None
examples list[Any] | None

Example values to use when including this computed field in JSON Schema

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

A dict or callable to provide extra JSON schema properties.

None
repr bool | None

whether to include this computed field in model repr. Default is False for private properties and True for public properties.

None
return_type Any

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.

PydanticUndefined

Returns:

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

A proxy wrapper for the property.

Source code in pydantic/fields.py
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
def computed_field(
    func: PropertyT | None = None,
    /,
    *,
    alias: str | None = None,
    alias_priority: int | None = None,
    exclude_if: Callable[[Any], bool] | 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
        exclude_if: A callable that determines whether to exclude this computed field during serialization based on its value.
        title: Title to use when including this computed field in JSON Schema
        field_title_generator: A callable that takes a field's name and info 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,
            exclude_if,
            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,
    exclude_if: Callable[[Any], bool] | 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,
)

A container for data from @computed_field so that we can access it while building the pydantic-core schema.

Attributes:

Name Type Description
decorator_repr str

A class variable representing the decorator string, '@computed_field'.

wrapped_property property

The wrapped computed field property.

return_type Any

The type of the computed field property's return value.

alias str | None

The alias of the property to be used during serialization.

alias_priority int | None

The priority of the alias. This affects whether an alias generator is used.

title str | None

Title of the computed field to include in the serialization JSON schema.

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

A callable that takes a field's name and info and returns title for it.

description str | None

Description of the computed field to include in the serialization JSON schema.

deprecated Deprecated | str | bool | None

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.

examples list[Any] | None

Example values of the computed field to include in the serialization JSON schema.

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

A dict or callable to provide extra JSON schema properties.

repr bool

A boolean indicating whether to include the field in the repr output.

deprecation_message property

deprecation_message: str | None

The deprecation message to be emitted, or None if not set.