Fields
Defining fields on models.
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,
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,
union_mode=_Unset,
**extra
)
Usage Documentation
Create a field for objects that can be configured.
Used to provide extra information about a field, either for the model schema or complex validation. Some arguments
apply only to number fields (int
, float
, Decimal
) and some apply only to str
.
Note
- Any
_Unset
objects will be replaced by the corresponding value defined in the_DefaultValues
dictionary. If a key for the_Unset
object is not found in the_DefaultValues
dictionary, it will default toNone
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: |
_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 serialization. |
_Unset
|
discriminator |
str | None
|
Field name for discriminating the type in a tagged union. |
_Unset
|
json_schema_extra |
dict[str, Any] | typing.Callable[[dict[str, Any]], None] | 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. This can be set to |
_Unset
|
repr |
bool
|
A boolean indicating whether to include the field in the |
_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 |
_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 |
_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
|
union_mode |
Literal['smart', 'left_to_right']
|
The strategy to apply when validating a union. Can be |
_Unset
|
extra |
Unpack[_EmptyKwargs]
|
Include extra fields used by the JSON schema. Warning The |
{}
|
Returns:
Type | Description |
---|---|
Any
|
A new |
Source code in pydantic/fields.py
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 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 |
|
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.
Warning
You generally shouldn't be creating FieldInfo
directly, you'll only need to use it when accessing
BaseModel
.model_fields
internals.
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 serialization. |
discriminator |
str | None
|
Field name for discriminating the type in a tagged union. |
json_schema_extra |
dict[str, Any] | typing.Callable[[dict[str, Any]], None] | 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
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 206 207 208 209 210 211 212 213 |
|
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
215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 |
|
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
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 |
|
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
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 |
|
merge_field_infos
staticmethod
¶
merge_field_infos(*field_infos, **overrides)
Merge FieldInfo
instances keeping only explicitly set attributes.
Later FieldInfo
instances override earlier ones.
Returns:
Name | Type | Description |
---|---|---|
FieldInfo |
FieldInfo
|
A merged FieldInfo instance. |
Source code in pydantic/fields.py
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 |
|
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
|
Returns:
Type | Description |
---|---|
Any
|
The default value, calling the default factory if requested or |
Source code in pydantic/fields.py
493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 |
|
is_required ¶
is_required()
Check if the argument is required.
Returns:
Type | Description |
---|---|
bool
|
|
Source code in pydantic/fields.py
513 514 515 516 517 518 519 |
|
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
521 522 523 524 525 526 527 528 529 530 531 532 533 534 |
|
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
536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 |
|
AliasChoices
dataclass
¶
AliasChoices(first_choice, *choices)
Usage Documentation
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 |
Source code in pydantic/fields.py
617 618 |
|
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
620 621 622 623 624 625 626 627 628 629 630 631 632 |
|
AliasPath
dataclass
¶
AliasPath(first_arg, *args)
Usage Documentation
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
593 594 |
|
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
596 597 598 599 600 601 602 |
|
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 |
None
|
Returns:
Type | Description |
---|---|
Any
|
An instance of |
Raises:
Type | Description |
---|---|
ValueError
|
If both |
Source code in pydantic/fields.py
920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 |
|
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
873 874 875 876 877 |
|
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
901 902 903 904 905 906 907 908 909 910 911 |
|
computed_field ¶
computed_field(
__f=None,
*,
alias=None,
alias_priority=None,
title=None,
description=None,
repr=None,
return_type=PydanticUndefined
)
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[misc]
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 ValueError as e:
print(repr(e))
#> ValueError("you can't override a field with a computed field")
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))
#> M(foo=1)
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 |
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 | None
|
whether to include this computed field in model repr.
Default is |
None
|
return_type |
Any
|
optional return for serialization logic to expect when serializing to JSON, if included
this must be correct, otherwise a |
PydanticUndefined
|
Returns:
Type | Description |
---|---|
PropertyT | typing.Callable[[PropertyT], PropertyT]
|
A proxy wrapper for the property. |
Source code in pydantic/fields.py
1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 |
|
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. |