Fields
Defining fields on models.
Field ¶
Field(
default: ellipsis,
*,
alias: str | None = _Unset,
alias_priority: int | None = _Unset,
validation_alias: (
str | AliasPath | AliasChoices | None
) = _Unset,
serialization_alias: str | None = _Unset,
title: str | None = _Unset,
field_title_generator: (
Callable[[str, FieldInfo], str] | None
) = _Unset,
description: str | None = _Unset,
examples: list[Any] | None = _Unset,
exclude: bool | None = _Unset,
exclude_if: Callable[[Any], bool] | None = _Unset,
discriminator: str | Discriminator | None = _Unset,
deprecated: Deprecated | str | bool | None = _Unset,
json_schema_extra: (
JsonDict | Callable[[JsonDict], None] | None
) = _Unset,
frozen: bool | None = _Unset,
validate_default: bool | None = _Unset,
repr: bool = _Unset,
init: bool | None = _Unset,
init_var: bool | None = _Unset,
kw_only: bool | None = _Unset,
pattern: str | Pattern[str] | None = _Unset,
strict: bool | None = _Unset,
coerce_numbers_to_str: bool | None = _Unset,
gt: SupportsGt | None = _Unset,
ge: SupportsGe | None = _Unset,
lt: SupportsLt | None = _Unset,
le: SupportsLe | None = _Unset,
multiple_of: float | None = _Unset,
allow_inf_nan: bool | None = _Unset,
max_digits: int | None = _Unset,
decimal_places: int | None = _Unset,
min_length: int | None = _Unset,
max_length: int | None = _Unset,
union_mode: Literal["smart", "left_to_right"] = _Unset,
fail_fast: bool | None = _Unset,
**extra: Unpack[_EmptyKwargs]
) -> Any
Field(
default: Any,
*,
alias: str | None = _Unset,
alias_priority: int | None = _Unset,
validation_alias: (
str | AliasPath | AliasChoices | None
) = _Unset,
serialization_alias: str | None = _Unset,
title: str | None = _Unset,
field_title_generator: (
Callable[[str, FieldInfo], str] | None
) = _Unset,
description: str | None = _Unset,
examples: list[Any] | None = _Unset,
exclude: bool | None = _Unset,
exclude_if: Callable[[Any], bool] | None = _Unset,
discriminator: str | Discriminator | None = _Unset,
deprecated: Deprecated | str | bool | None = _Unset,
json_schema_extra: (
JsonDict | Callable[[JsonDict], None] | None
) = _Unset,
frozen: bool | None = _Unset,
validate_default: Literal[True],
repr: bool = _Unset,
init: bool | None = _Unset,
init_var: bool | None = _Unset,
kw_only: bool | None = _Unset,
pattern: str | Pattern[str] | None = _Unset,
strict: bool | None = _Unset,
coerce_numbers_to_str: bool | None = _Unset,
gt: SupportsGt | None = _Unset,
ge: SupportsGe | None = _Unset,
lt: SupportsLt | None = _Unset,
le: SupportsLe | None = _Unset,
multiple_of: float | None = _Unset,
allow_inf_nan: bool | None = _Unset,
max_digits: int | None = _Unset,
decimal_places: int | None = _Unset,
min_length: int | None = _Unset,
max_length: int | None = _Unset,
union_mode: Literal["smart", "left_to_right"] = _Unset,
fail_fast: bool | None = _Unset,
**extra: Unpack[_EmptyKwargs]
) -> Any
Field(
default: _T,
*,
alias: str | None = _Unset,
alias_priority: int | None = _Unset,
validation_alias: (
str | AliasPath | AliasChoices | None
) = _Unset,
serialization_alias: str | None = _Unset,
title: str | None = _Unset,
field_title_generator: (
Callable[[str, FieldInfo], str] | None
) = _Unset,
description: str | None = _Unset,
examples: list[Any] | None = _Unset,
exclude: bool | None = _Unset,
exclude_if: Callable[[Any], bool] | None = _Unset,
discriminator: str | Discriminator | None = _Unset,
deprecated: Deprecated | str | bool | None = _Unset,
json_schema_extra: (
JsonDict | Callable[[JsonDict], None] | None
) = _Unset,
frozen: bool | None = _Unset,
validate_default: Literal[False] = ...,
repr: bool = _Unset,
init: bool | None = _Unset,
init_var: bool | None = _Unset,
kw_only: bool | None = _Unset,
pattern: str | Pattern[str] | None = _Unset,
strict: bool | None = _Unset,
coerce_numbers_to_str: bool | None = _Unset,
gt: SupportsGt | None = _Unset,
ge: SupportsGe | None = _Unset,
lt: SupportsLt | None = _Unset,
le: SupportsLe | None = _Unset,
multiple_of: float | None = _Unset,
allow_inf_nan: bool | None = _Unset,
max_digits: int | None = _Unset,
decimal_places: int | None = _Unset,
min_length: int | None = _Unset,
max_length: int | None = _Unset,
union_mode: Literal["smart", "left_to_right"] = _Unset,
fail_fast: bool | None = _Unset,
**extra: Unpack[_EmptyKwargs]
) -> _T
Field(
*,
default_factory: (
Callable[[], Any] | Callable[[dict[str, Any]], Any]
),
alias: str | None = _Unset,
alias_priority: int | None = _Unset,
validation_alias: (
str | AliasPath | AliasChoices | None
) = _Unset,
serialization_alias: str | None = _Unset,
title: str | None = _Unset,
field_title_generator: (
Callable[[str, FieldInfo], str] | None
) = _Unset,
description: str | None = _Unset,
examples: list[Any] | None = _Unset,
exclude: bool | None = _Unset,
exclude_if: Callable[[Any], bool] | None = _Unset,
discriminator: str | Discriminator | None = _Unset,
deprecated: Deprecated | str | bool | None = _Unset,
json_schema_extra: (
JsonDict | Callable[[JsonDict], None] | None
) = _Unset,
frozen: bool | None = _Unset,
validate_default: Literal[True],
repr: bool = _Unset,
init: bool | None = _Unset,
init_var: bool | None = _Unset,
kw_only: bool | None = _Unset,
pattern: str | Pattern[str] | None = _Unset,
strict: bool | None = _Unset,
coerce_numbers_to_str: bool | None = _Unset,
gt: SupportsGt | None = _Unset,
ge: SupportsGe | None = _Unset,
lt: SupportsLt | None = _Unset,
le: SupportsLe | None = _Unset,
multiple_of: float | None = _Unset,
allow_inf_nan: bool | None = _Unset,
max_digits: int | None = _Unset,
decimal_places: int | None = _Unset,
min_length: int | None = _Unset,
max_length: int | None = _Unset,
union_mode: Literal["smart", "left_to_right"] = _Unset,
fail_fast: bool | None = _Unset,
**extra: Unpack[_EmptyKwargs]
) -> Any
Field(
*,
default_factory: (
Callable[[], _T] | Callable[[dict[str, Any]], _T]
),
alias: str | None = _Unset,
alias_priority: int | None = _Unset,
validation_alias: (
str | AliasPath | AliasChoices | None
) = _Unset,
serialization_alias: str | None = _Unset,
title: str | None = _Unset,
field_title_generator: (
Callable[[str, FieldInfo], str] | None
) = _Unset,
description: str | None = _Unset,
examples: list[Any] | None = _Unset,
exclude: bool | None = _Unset,
exclude_if: Callable[[Any], bool] | None = _Unset,
discriminator: str | Discriminator | None = _Unset,
deprecated: Deprecated | str | bool | None = _Unset,
json_schema_extra: (
JsonDict | Callable[[JsonDict], None] | None
) = _Unset,
frozen: bool | None = _Unset,
validate_default: Literal[False] | None = _Unset,
repr: bool = _Unset,
init: bool | None = _Unset,
init_var: bool | None = _Unset,
kw_only: bool | None = _Unset,
pattern: str | Pattern[str] | None = _Unset,
strict: bool | None = _Unset,
coerce_numbers_to_str: bool | None = _Unset,
gt: SupportsGt | None = _Unset,
ge: SupportsGe | None = _Unset,
lt: SupportsLt | None = _Unset,
le: SupportsLe | None = _Unset,
multiple_of: float | None = _Unset,
allow_inf_nan: bool | None = _Unset,
max_digits: int | None = _Unset,
decimal_places: int | None = _Unset,
min_length: int | None = _Unset,
max_length: int | None = _Unset,
union_mode: Literal["smart", "left_to_right"] = _Unset,
fail_fast: bool | None = _Unset,
**extra: Unpack[_EmptyKwargs]
) -> _T
Field(
*,
alias: str | None = _Unset,
alias_priority: int | None = _Unset,
validation_alias: (
str | AliasPath | AliasChoices | None
) = _Unset,
serialization_alias: str | None = _Unset,
title: str | None = _Unset,
field_title_generator: (
Callable[[str, FieldInfo], str] | None
) = _Unset,
description: str | None = _Unset,
examples: list[Any] | None = _Unset,
exclude: bool | None = _Unset,
exclude_if: Callable[[Any], bool] | None = _Unset,
discriminator: str | Discriminator | None = _Unset,
deprecated: Deprecated | str | bool | None = _Unset,
json_schema_extra: (
JsonDict | Callable[[JsonDict], None] | None
) = _Unset,
frozen: bool | None = _Unset,
validate_default: bool | None = _Unset,
repr: bool = _Unset,
init: bool | None = _Unset,
init_var: bool | None = _Unset,
kw_only: bool | None = _Unset,
pattern: str | Pattern[str] | None = _Unset,
strict: bool | None = _Unset,
coerce_numbers_to_str: bool | None = _Unset,
gt: SupportsGt | None = _Unset,
ge: SupportsGe | None = _Unset,
lt: SupportsLt | None = _Unset,
le: SupportsLe | None = _Unset,
multiple_of: float | None = _Unset,
allow_inf_nan: bool | None = _Unset,
max_digits: int | None = _Unset,
decimal_places: int | None = _Unset,
min_length: int | None = _Unset,
max_length: int | None = _Unset,
union_mode: Literal["smart", "left_to_right"] = _Unset,
fail_fast: bool | None = _Unset,
**extra: Unpack[_EmptyKwargs]
) -> Any
Field(
default: Any = PydanticUndefined,
*,
default_factory: (
Callable[[], Any]
| Callable[[dict[str, Any]], Any]
| None
) = _Unset,
alias: str | None = _Unset,
alias_priority: int | None = _Unset,
validation_alias: (
str | AliasPath | AliasChoices | None
) = _Unset,
serialization_alias: str | None = _Unset,
title: str | None = _Unset,
field_title_generator: (
Callable[[str, FieldInfo], str] | None
) = _Unset,
description: str | None = _Unset,
examples: list[Any] | None = _Unset,
exclude: bool | None = _Unset,
exclude_if: Callable[[Any], bool] | None = _Unset,
discriminator: str | Discriminator | None = _Unset,
deprecated: Deprecated | str | bool | None = _Unset,
json_schema_extra: (
JsonDict | Callable[[JsonDict], None] | None
) = _Unset,
frozen: bool | None = _Unset,
validate_default: bool | None = _Unset,
repr: bool = _Unset,
init: bool | None = _Unset,
init_var: bool | None = _Unset,
kw_only: bool | None = _Unset,
pattern: str | Pattern[str] | None = _Unset,
strict: bool | None = _Unset,
coerce_numbers_to_str: bool | None = _Unset,
gt: SupportsGt | None = _Unset,
ge: SupportsGe | None = _Unset,
lt: SupportsLt | None = _Unset,
le: SupportsLe | None = _Unset,
multiple_of: float | None = _Unset,
allow_inf_nan: bool | None = _Unset,
max_digits: int | None = _Unset,
decimal_places: int | None = _Unset,
min_length: int | None = _Unset,
max_length: int | None = _Unset,
union_mode: Literal["smart", "left_to_right"] = _Unset,
fail_fast: bool | None = _Unset,
**extra: Unpack[_EmptyKwargs]
) -> Any
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
|
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 |
_Unset
|
serialization_alias
|
str | None
|
Like |
_Unset
|
title
|
str | None
|
Human-readable title. |
_Unset
|
field_title_generator
|
Callable[[str, FieldInfo], str] | None
|
A callable that takes a field name 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 |
_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 |
_Unset
|
repr
|
bool
|
A boolean indicating whether to include the field in the |
_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 |
_Unset
|
strict
|
bool | None
|
If |
_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 |
_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
|
fail_fast
|
bool | None
|
If |
_Unset
|
extra
|
Unpack[_EmptyKwargs]
|
(Deprecated) Extra fields that will be included in the JSON schema. Warning The |
{}
|
Returns:
Type | Description |
---|---|
Any
|
A new |
Source code in pydantic/fields.py
1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 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 |
|
FieldInfo ¶
FieldInfo(**kwargs: Unpack[_FieldInfoInputs])
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 |
type[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 name 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 |
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
|
See the signature of pydantic.fields.Field
for more details about the expected arguments.
Source code in pydantic/fields.py
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 |
|
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: 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 |
Source code in pydantic/fields.py
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 |
|
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
|
|
Source code in pydantic/fields.py
751 752 753 754 755 756 757 |
|
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 remainingFieldInfo
attributes to their values (e.g.alias
,title
).
Source code in pydantic/fields.py
806 807 808 809 810 811 812 813 814 815 816 817 818 819 |
|
PrivateAttr ¶
PrivateAttr(
default: _T, *, init: Literal[False] = False
) -> _T
PrivateAttr(
default: Any = PydanticUndefined,
*,
default_factory: Callable[[], Any] | None = None,
init: Literal[False] = False
) -> Any
Usage Documentation
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] | None
|
Callable that will be
called when a default value is needed for this attribute.
If both |
None
|
init
|
Literal[False]
|
Whether the attribute should be included in the constructor of the dataclass. Always |
False
|
Returns:
Type | Description |
---|---|
Any
|
An instance of |
Raises:
Type | Description |
---|---|
ValueError
|
If both |
Source code in pydantic/fields.py
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 |
|
ModelPrivateAttr ¶
ModelPrivateAttr(
default: Any = PydanticUndefined,
*,
default_factory: Callable[[], 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
pydantic.fields.PrivateAttr
. (This is similar to FieldInfo
vs. Field
.)
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
1415 1416 1417 1418 1419 1420 |
|
__getattr__ ¶
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
1425 1426 1427 1428 1429 1430 1431 1432 |
|
__set_name__ ¶
Preserve __set_name__
protocol defined in https://peps.python.org/pep-0487.
Source code in pydantic/fields.py
1434 1435 1436 1437 1438 1439 1440 1441 |
|
get_default ¶
get_default() -> 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:
Type | Description |
---|---|
Any
|
The default value of the object. |
Source code in pydantic/fields.py
1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 |
|
computed_field ¶
computed_field(func: PropertyT) -> PropertyT
computed_field(
*,
alias: str | None = None,
alias_priority: int | None = None,
title: str | None = None,
field_title_generator: (
Callable[[str, ComputedFieldInfo], str] | None
) = None,
description: str | None = None,
deprecated: Deprecated | str | bool | None = None,
examples: list[Any] | None = None,
json_schema_extra: (
JsonDict | Callable[[JsonDict], None] | None
) = None,
repr: bool = True,
return_type: Any = PydanticUndefined
) -> Callable[[PropertyT], PropertyT]
computed_field(
func: PropertyT | None = None,
/,
*,
alias: str | None = None,
alias_priority: int | None = None,
title: str | None = None,
field_title_generator: (
Callable[[str, ComputedFieldInfo], str] | None
) = None,
description: str | None = None,
deprecated: Deprecated | str | bool | None = None,
examples: list[Any] | None = None,
json_schema_extra: (
JsonDict | Callable[[JsonDict], None] | None
) = None,
repr: bool | None = None,
return_type: Any = PydanticUndefined,
) -> PropertyT | Callable[[PropertyT], PropertyT]
Usage Documentation
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 |
None
|
alias_priority
|
int | None
|
priority of the alias. This affects whether an alias generator is used |
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 name 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 |
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 |
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 | Callable[[PropertyT], PropertyT]
|
A proxy wrapper for the property. |
Source code in pydantic/fields.py
1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 |
|
ComputedFieldInfo
dataclass
¶
ComputedFieldInfo(
wrapped_property: property,
return_type: Any,
alias: str | None,
alias_priority: int | None,
title: str | None,
field_title_generator: (
Callable[[str, ComputedFieldInfo], str] | None
),
description: str | None,
deprecated: Deprecated | str | bool | None,
examples: list[Any] | None,
json_schema_extra: (
JsonDict | Callable[[JsonDict], None] | None
),
repr: bool,
)
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 name 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 |
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. |