Skip to content

pydantic.fields

Defining fields on models.

AliasChoices dataclass

AliasChoices(first_choice, *choices)

Usage Documentation

AliasPath and AliasChoices

A data class used by validation_alias as a convenience to create aliases.

Attributes:

Name Type Description
choices list[str | AliasPath]

A list containing a string or AliasPath.

Source code in pydantic/fields.py
583
584
def __init__(self, first_choice: str | AliasPath, *choices: str | AliasPath) -> None:
    self.choices = [first_choice] + list(choices)

convert_to_aliases

convert_to_aliases()

Converts arguments to a list of lists containing string or integer aliases.

Returns:

Type Description
list[list[str | int]]

The list of aliases.

Source code in pydantic/fields.py
586
587
588
589
590
591
592
593
594
595
596
597
598
def convert_to_aliases(self) -> list[list[str | int]]:
    """Converts arguments to a list of lists containing string or integer aliases.

    Returns:
        The list of aliases.
    """
    aliases: list[list[str | int]] = []
    for c in self.choices:
        if isinstance(c, AliasPath):
            aliases.append(c.convert_to_aliases())
        else:
            aliases.append([c])
    return aliases

AliasPath dataclass

AliasPath(first_arg, *args)

Usage Documentation

AliasPath and AliasChoices

A data class used by validation_alias as a convenience to create aliases.

Attributes:

Name Type Description
path list[int | str]

A list of string or integer aliases.

Source code in pydantic/fields.py
559
560
def __init__(self, first_arg: str, *args: str | int) -> None:
    self.path = [first_arg] + list(args)

convert_to_aliases

convert_to_aliases()

Converts arguments to a list of string or integer aliases.

Returns:

Type Description
list[str | int]

The list of aliases.

Source code in pydantic/fields.py
562
563
564
565
566
567
568
def convert_to_aliases(self) -> list[str | int]:
    """Converts arguments to a list of string or integer aliases.

    Returns:
        The list of aliases.
    """
    return self.path

ComputedFieldInfo dataclass

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 encoding and decoding.

alias_priority int | None

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

title str | None

Title of the computed field as in OpenAPI document, should be a short summary.

description str | None

Description of the computed field as in OpenAPI document.

repr bool

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

FieldInfo

FieldInfo(**kwargs)

Bases: _repr.Representation

This class holds information about a field.

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

Attributes:

Name Type Description
annotation type[Any] | None

The type annotation of the field.

default Any

The default value of the field.

default_factory typing.Callable[[], Any] | None

The factory function used to construct the default for the field.

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 name of the field.

serialization_alias str | None

The serialization alias name of the field.

title str | None

The title of the field.

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

include bool | None

Whether to include the field in the model schema.

discriminator str | None

Field name for discriminating the type in a tagged union.

json_schema_extra dict[str, Any] | None

Dictionary of 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_var bool | None

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

kw_only bool | None

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

metadata list[Any]

List of metadata constraints.

See the signature of pydantic.fields.Field for more details about the expected arguments.

Source code in pydantic/fields.py
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
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}
    kwargs = {k: _DefaultValues.get(k) if v is _Unset else v for k, v in kwargs.items()}  # type: ignore
    self.annotation, annotation_metadata = self._extract_metadata(kwargs.get('annotation'))

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

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

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

    self.title = kwargs.pop('title', None)
    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.description = kwargs.pop('description', None)
    self.examples = kwargs.pop('examples', None)
    self.exclude = kwargs.pop('exclude', None)
    self.include = kwargs.pop('include', None)
    self.discriminator = kwargs.pop('discriminator', 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_var = kwargs.pop('init_var', None)
    self.kw_only = kwargs.pop('kw_only', None)

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

apply_typevars_map

apply_typevars_map(typevars_map, types_namespace)

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.

Parameters:

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

A dictionary mapping type variables to their concrete types.

required
types_namespace dict | None

A dictionary containing related types to the annotated type.

required
See Also

pydantic._internal._generics.replace_types is used for replacing the typevars with their concrete types.

Source code in pydantic/fields.py
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
def apply_typevars_map(self, typevars_map: dict[Any, Any] | None, types_namespace: dict[str, Any] | 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.
        types_namespace (dict | None): A dictionary containing related types to the annotated type.

    See Also:
        pydantic._internal._generics.replace_types is used for replacing the typevars with
            their concrete types.
    """
    annotation = _typing_extra.eval_type_lenient(self.annotation, types_namespace, None)
    self.annotation = _generics.replace_types(annotation, typevars_map)

from_annotated_attribute classmethod

from_annotated_attribute(annotation, default)

Create FieldInfo from an annotation with a default value.

Parameters:

Name Type Description Default
annotation type[Any]

The type annotation of the field.

required
default Any

The default value of the field.

required

Returns:

Type Description
typing_extensions.Self

A field object with the passed values.

Example
import annotated_types
from typing_extensions import Annotated

import pydantic

class MyModel(pydantic.BaseModel):
    foo: int = 4  # <-- like this
    bar: Annotated[int, annotated_types.Gt(4)] = 4  # <-- or this
    spam: Annotated[int, pydantic.Field(gt=4)] = 4  # <-- or this
Source code in pydantic/fields.py
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
@classmethod
def from_annotated_attribute(cls, annotation: type[Any], default: Any) -> typing_extensions.Self:
    """Create `FieldInfo` from an annotation with a default value.

    Args:
        annotation: The type annotation of the field.
        default: The default value of the field.

    Returns:
        A field object with the passed values.

    Example:
        ```python
        import annotated_types
        from typing_extensions import Annotated

        import pydantic

        class MyModel(pydantic.BaseModel):
            foo: int = 4  # <-- like this
            bar: Annotated[int, annotated_types.Gt(4)] = 4  # <-- or this
            spam: Annotated[int, pydantic.Field(gt=4)] = 4  # <-- or this
        ```
    """
    final = False
    if _typing_extra.is_finalvar(annotation):
        final = True
        if annotation is not typing_extensions.Final:
            annotation = typing_extensions.get_args(annotation)[0]

    if isinstance(default, cls):
        default.annotation, annotation_metadata = cls._extract_metadata(annotation)
        default.metadata += annotation_metadata
        default.frozen = final or default.frozen
        return default
    elif isinstance(default, dataclasses.Field):
        init_var = False
        if annotation is dataclasses.InitVar:
            if sys.version_info < (3, 8):
                raise RuntimeError('InitVar is not supported in Python 3.7 as type information is lost')

            init_var = True
            annotation = Any
        elif isinstance(annotation, dataclasses.InitVar):
            init_var = True
            annotation = annotation.type
        pydantic_field = cls._from_dataclass_field(default)
        pydantic_field.annotation, annotation_metadata = cls._extract_metadata(annotation)
        pydantic_field.metadata += annotation_metadata
        pydantic_field.frozen = final or pydantic_field.frozen
        pydantic_field.init_var = init_var
        pydantic_field.kw_only = getattr(default, 'kw_only', None)
        return pydantic_field
    else:
        if _typing_extra.is_annotated(annotation):
            first_arg, *extra_args = typing_extensions.get_args(annotation)
            field_infos = [a for a in extra_args if isinstance(a, FieldInfo)]
            field_info = cls.merge_field_infos(*field_infos, annotation=first_arg, default=default)
            field_info.metadata += [a for a in extra_args if not isinstance(a, FieldInfo)]
            return field_info

        return cls(annotation=annotation, default=default, frozen=final or None)

from_annotation classmethod

from_annotation(annotation)

Creates a FieldInfo instance from a bare annotation.

Parameters:

Name Type Description Default
annotation type[Any]

An annotation object.

required

Returns:

Type Description
typing_extensions.Self

An instance of the field metadata.

Example

This is how you can create a field from a bare annotation like this:

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 are an instance of FieldInfo, e.g.:

import annotated_types
from typing_extensions import Annotated

import pydantic

class MyModel(pydantic.BaseModel):
    foo: Annotated[int, annotated_types.Gt(42)]
    bar: Annotated[int, pydantic.Field(gt=42)]
Source code in pydantic/fields.py
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
@classmethod
def from_annotation(cls, annotation: type[Any]) -> typing_extensions.Self:
    """Creates a `FieldInfo` instance from a bare annotation.

    Args:
        annotation: An annotation object.

    Returns:
        An instance of the field metadata.

    Example:
        This is how you can create a field 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` are an instance of `FieldInfo`, e.g.:

        ```python
        import annotated_types
        from typing_extensions import Annotated

        import pydantic

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

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

    if _typing_extra.is_annotated(annotation):
        first_arg, *extra_args = typing_extensions.get_args(annotation)
        if _typing_extra.is_finalvar(first_arg):
            final = True
        field_info = cls._find_field_info_arg(extra_args)
        if field_info:
            new_field_info = copy(field_info)
            new_field_info.annotation = first_arg
            new_field_info.frozen = final or field_info.frozen
            new_field_info.metadata += [a for a in extra_args if not isinstance(a, FieldInfo)]
            return new_field_info

    return cls(annotation=annotation, frozen=final or None)

from_field classmethod

from_field(default=PydanticUndefined, **kwargs)

Create a new FieldInfo object with the Field function.

Parameters:

Name Type Description Default
default Any

The default value for the field. Defaults to Undefined.

PydanticUndefined
**kwargs Unpack[_FromFieldInfoInputs]

Additional arguments dictionary.

{}

Raises:

Type Description
TypeError

If 'annotation' is passed as a keyword argument.

Returns:

Type Description
typing_extensions.Self

A new FieldInfo object with the given parameters.

Example

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

import pydantic

class MyModel(pydantic.BaseModel):
    foo: int = pydantic.Field(4)
Source code in pydantic/fields.py
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
@classmethod
def from_field(
    cls, default: Any = PydanticUndefined, **kwargs: Unpack[_FromFieldInfoInputs]
) -> typing_extensions.Self:
    """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 cls(default=default, **kwargs)

get_default

get_default(*, call_default_factory=False)

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. Defaults to False.

False

Returns:

Type Description
Any

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

Source code in pydantic/fields.py
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
def get_default(self, *, call_default_factory: bool = False) -> 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. Defaults to `False`.

    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:
        return self.default_factory()
    else:
        return None

is_required

is_required()

Check if the argument is required.

Returns:

Type Description
bool

True if the argument is required, False otherwise.

Source code in pydantic/fields.py
479
480
481
482
483
484
485
def is_required(self) -> bool:
    """Check if the argument is required.

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

merge_field_infos staticmethod

merge_field_infos(*field_infos, **overrides)

Merge FieldInfo instances keeping only explicitly set attributes.

Returns:

Name Type Description
FieldInfo FieldInfo

A merged FieldInfo instance.

Source code in pydantic/fields.py
355
356
357
358
359
360
361
362
363
364
365
366
@staticmethod
def merge_field_infos(*field_infos: FieldInfo, **overrides: Any) -> FieldInfo:
    """Merge `FieldInfo` instances keeping only explicitly set attributes.

    Returns:
        FieldInfo: A merged FieldInfo instance.
    """
    new_kwargs: dict[str, Any] = {}
    for field_info in field_infos:
        new_kwargs.update(field_info._attributes_set)
    new_kwargs.update(overrides)
    return FieldInfo(**new_kwargs)

rebuild_annotation

rebuild_annotation()

Rebuilds the original annotation for use in function signatures.

If metadata is present, it adds it to the original annotation using an AnnotatedAlias. Otherwise, it returns the original annotation as is.

Returns:

Type Description
Any

The rebuilt annotation.

Source code in pydantic/fields.py
487
488
489
490
491
492
493
494
495
496
497
498
499
500
def rebuild_annotation(self) -> Any:
    """Rebuilds the original annotation for use in function signatures.

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

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

ModelPrivateAttr

ModelPrivateAttr(
    default=PydanticUndefined, *, default_factory=None
)

Bases: _repr.Representation

A descriptor for private attributes in class models.

Attributes:

Name Type Description
default

The default value of the attribute if not provided.

default_factory

A callable function that generates the default value of the attribute if not provided.

Source code in pydantic/fields.py
827
828
829
830
831
def __init__(
    self, default: Any = PydanticUndefined, *, default_factory: typing.Callable[[], Any] | None = None
) -> None:
    self.default = default
    self.default_factory = default_factory

get_default

get_default()

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:

Type Description
Any

The default value of the object.

Source code in pydantic/fields.py
855
856
857
858
859
860
861
862
863
864
865
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()

Field

Field(
    default=PydanticUndefined,
    *,
    default_factory=_Unset,
    alias=_Unset,
    alias_priority=_Unset,
    validation_alias=_Unset,
    serialization_alias=_Unset,
    title=_Unset,
    description=_Unset,
    examples=_Unset,
    exclude=_Unset,
    include=_Unset,
    discriminator=_Unset,
    json_schema_extra=_Unset,
    frozen=_Unset,
    validate_default=_Unset,
    repr=_Unset,
    init_var=_Unset,
    kw_only=_Unset,
    pattern=_Unset,
    strict=_Unset,
    gt=_Unset,
    ge=_Unset,
    lt=_Unset,
    le=_Unset,
    multiple_of=_Unset,
    allow_inf_nan=_Unset,
    max_digits=_Unset,
    decimal_places=_Unset,
    min_length=_Unset,
    max_length=_Unset,
    **extra
)

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.

Parameters:

Name Type Description Default
default Any

Default value if the field is not set.

PydanticUndefined
default_factory typing.Callable[[], Any] | None

A callable to generate the default value, such as :func:~datetime.utcnow.

_Unset
alias str | None

An alternative name for the attribute.

_Unset
alias_priority int | None

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

_Unset
validation_alias str | AliasPath | AliasChoices | None

'Whitelist' validation step. The field will be the single one allowed by the alias or set of aliases defined.

_Unset
serialization_alias str | None

'Blacklist' validation step. The vanilla field will be the single one of the alias' or set of aliases' fields and all the other fields will be ignored at serialization time.

_Unset
title str | None

Human-readable title.

_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 schema.

_Unset
include bool | None

Whether to include the field in the model schema.

_Unset
discriminator str | None

Field name for discriminating the type in a tagged union.

_Unset
json_schema_extra dict[str, Any] | None

Any additional JSON schema data for the schema property.

_Unset
frozen bool | None

Whether the field is frozen.

_Unset
validate_default bool | None

Run validation that isn't only checking existence of defaults. True by default.

_Unset
repr bool

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

_Unset
init_var bool | None

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

_Unset
kw_only bool | None

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

_Unset
strict bool | None

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

_Unset
gt float | None

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

_Unset
ge float | None

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

_Unset
lt float | None

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

_Unset
le float | 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 strings.

_Unset
max_length int | None

Maximum length for strings.

_Unset
pattern str | None

Pattern for strings.

_Unset
allow_inf_nan bool | None

Allow inf, -inf, nan. Only applicable to numbers.

_Unset
max_digits int | None

Maximum number of allow digits for strings.

_Unset
decimal_places int | None

Maximum number of decimal places allowed for numbers.

_Unset
extra Unpack[_EmptyKwargs]

Include extra fields used by the JSON schema.

Warning

The extra kwargs is deprecated. Use json_schema_extra instead.

{}

Returns:

Type Description
Any

The generated FieldInfo object

Source code in pydantic/fields.py
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
def Field(  # noqa: C901
    default: Any = PydanticUndefined,
    *,
    default_factory: typing.Callable[[], Any] | None = _Unset,
    alias: str | None = _Unset,
    alias_priority: int | None = _Unset,
    validation_alias: str | AliasPath | AliasChoices | None = _Unset,
    serialization_alias: str | None = _Unset,
    title: str | None = _Unset,
    description: str | None = _Unset,
    examples: list[Any] | None = _Unset,
    exclude: bool | None = _Unset,
    include: bool | None = _Unset,
    discriminator: str | None = _Unset,
    json_schema_extra: dict[str, Any] | None = _Unset,
    frozen: bool | None = _Unset,
    validate_default: bool | None = _Unset,
    repr: bool = _Unset,
    init_var: bool | None = _Unset,
    kw_only: bool | None = _Unset,
    pattern: str | None = _Unset,
    strict: bool | None = _Unset,
    gt: float | None = _Unset,
    ge: float | None = _Unset,
    lt: float | None = _Unset,
    le: float | 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,
    **extra: Unpack[_EmptyKwargs],
) -> Any:
    """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`.

    Args:
        default: Default value if the field is not set.
        default_factory: A callable to generate the default value, such as :func:`~datetime.utcnow`.
        alias: An alternative name for the attribute.
        alias_priority: Priority of the alias. This affects whether an alias generator is used.
        validation_alias: 'Whitelist' validation step. The field will be the single one allowed by the alias or set of
            aliases defined.
        serialization_alias: 'Blacklist' validation step. The vanilla field will be the single one of the alias' or set
            of aliases' fields and all the other fields will be ignored at serialization time.
        title: Human-readable title.
        description: Human-readable description.
        examples: Example values for this field.
        exclude: Whether to exclude the field from the model schema.
        include: Whether to include the field in the model schema.
        discriminator: Field name for discriminating the type in a tagged union.
        json_schema_extra: Any additional JSON schema data for the schema property.
        frozen: Whether the field is frozen.
        validate_default: Run validation that isn't only checking existence of defaults. `True` by default.
        repr: A boolean indicating whether to include the field in the `__repr__` output.
        init_var: Whether the field should be included in the constructor of the dataclass.
        kw_only: Whether the field should be a keyword-only argument in the constructor of the dataclass.
        strict: If `True`, strict validation is applied to the field.
            See [Strict Mode](../usage/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 strings.
        max_length: Maximum length for strings.
        pattern: Pattern for strings.
        allow_inf_nan: Allow `inf`, `-inf`, `nan`. Only applicable to numbers.
        max_digits: Maximum number of allow digits for strings.
        decimal_places: Maximum number of decimal places allowed for numbers.
        extra: Include extra fields used by the JSON schema.

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

    Returns:
        The generated `FieldInfo` object
    """
    # Check deprecated and removed params from V1. This logic should eventually be removed.
    const = extra.pop('const', None)  # type: ignore
    if const is not None:
        raise PydanticUserError('`const` is removed, use `Literal` instead', code='removed-kwargs')

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

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

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

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

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

    if extra:
        warn(
            'Extra keyword arguments on `Field` is deprecated and will be removed. use `json_schema_extra` instead',
            DeprecationWarning,
        )
        if not json_schema_extra or json_schema_extra is _Unset:
            json_schema_extra = extra  # type: ignore

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

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

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

    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,
        description=description,
        examples=examples,
        exclude=exclude,
        include=include,
        discriminator=discriminator,
        json_schema_extra=json_schema_extra,
        frozen=frozen,
        pattern=pattern,
        validate_default=validate_default,
        repr=repr,
        init_var=init_var,
        kw_only=kw_only,
        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,
    )

PrivateAttr

PrivateAttr(
    default=PydanticUndefined, *, default_factory=None
)

Indicates that attribute is only used internally and never mixed with regular fields.

Private attributes are not checked by Pydantic, so it's up to you to maintain their accuracy.

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 typing.Callable[[], Any] | None

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.

None

Returns:

Type Description
Any

An instance of ModelPrivateAttr class.

Raises:

Type Description
ValueError

If both default and default_factory are set.

Source code in pydantic/fields.py
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
def PrivateAttr(
    default: Any = PydanticUndefined,
    *,
    default_factory: typing.Callable[[], Any] | None = None,
) -> Any:
    """Indicates that attribute is only used internally and never mixed with regular fields.

    Private attributes are not checked by Pydantic, so it's up to you to maintain their accuracy.

    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.

    Returns:
        An instance of `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,
    )

computed_field

computed_field(
    __f=None,
    *,
    alias=None,
    alias_priority=None,
    title=None,
    description=None,
    repr=True,
    return_type=PydanticUndefined
)

Decorator to include property and cached_property when serializing models.

If applied to functions not yet decorated with @property or @cached_property, the function is automatically wrapped with property.

See Computed Fields for more details.

Parameters:

Name Type Description Default
__f 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
title str | None

Title to used when including this computed field in JSON Schema, currently unused waiting for #4697

None
description str | None

Description to used when including this computed field in JSON Schema, defaults to the functions docstring, currently unused waiting for #4697

None
repr bool

whether to include this computed field in model repr

True
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 | typing.Callable[[PropertyT], PropertyT]

A proxy wrapper for the property.

Source code in pydantic/fields.py
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
def computed_field(
    __f: PropertyT | None = None,
    *,
    alias: str | None = None,
    alias_priority: int | None = None,
    title: str | None = None,
    description: str | None = None,
    repr: bool = True,
    return_type: Any = PydanticUndefined,
) -> PropertyT | typing.Callable[[PropertyT], PropertyT]:
    """Decorator to include `property` and `cached_property` when serializing models.

    If applied to functions not yet decorated with `@property` or `@cached_property`, the function is
    automatically wrapped with `property`.

    See [Computed Fields](../usage/computed_fields.md) for more details.

    Args:
        __f: 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 used when including this computed field in JSON Schema, currently unused waiting for #4697
        description: Description to used when including this computed field in JSON Schema, defaults to the functions
            docstring, currently unused waiting for #4697
        repr: whether to include this computed field in model repr
        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, return_type, alias_priority
        unwrapped = _decorators.unwrap_wrapped_function(f)
        if description is None and unwrapped.__doc__:
            description = inspect.cleandoc(unwrapped.__doc__)

        # 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
        dec_info = ComputedFieldInfo(f, return_type, alias, alias_priority, title, description, repr)
        return _decorators.PydanticDescriptorProxy(f, dec_info)

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