字段
在模型上定义字段。
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,
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: _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,
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]
) -> _T
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,
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]
) -> _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,
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,
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
用法文档
为可配置的对象创建字段。
用于提供关于字段的额外信息,无论是为了模型模式还是复杂的验证。一些参数仅适用于数字字段 (int
, float
, Decimal
),另一些仅适用于 str
。
注意
- 任何
_Unset
对象都将被_DefaultValues
字典中定义的相应值替换。如果在_DefaultValues
字典中找不到_Unset
对象的键,则默认值为None
参数
名称 | 类型 | 描述 | 默认值 |
---|---|---|---|
default
|
Any
|
如果字段未设置,则为默认值。 |
PydanticUndefined
|
default_factory
|
Callable[[], Any] | Callable[[dict[str, Any]], Any] | None
|
用于生成默认值的可调用对象。该可调用对象可以接受 0 个参数(在这种情况下,它会被直接调用)或单个参数,其中包含已验证的数据。 |
_Unset
|
alias
|
str | None
|
在通过别名验证或序列化时,用于属性的名称。这通常用于在 snake case 和 camel case 之间进行转换等操作。 |
_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
|
discriminator
|
str | Discriminator | None
|
用于区分标记联合类型的字段名称或 Discriminator。 |
_Unset
|
deprecated
|
Deprecated | str | bool | None
|
弃用消息、 |
_Unset
|
json_schema_extra
|
JsonDict | Callable[[JsonDict], None] | None
|
用于提供额外 JSON schema 属性的字典或可调用对象。 |
_Unset
|
frozen
|
bool | None
|
字段是否为冻结状态。如果为 true,则尝试更改实例上的值将引发错误。 |
_Unset
|
validate_default
|
bool | None
|
如果为 |
_Unset
|
repr
|
bool
|
一个布尔值,指示是否在 |
_Unset
|
init
|
bool | None
|
字段是否应包含在数据类的构造函数中。(仅适用于数据类。) |
_Unset
|
init_var
|
bool | None
|
字段是否应该仅包含在数据类的构造函数中。(仅适用于数据类。) |
_Unset
|
kw_only
|
bool | None
|
字段是否应为数据类构造函数中的仅关键字参数。(仅适用于数据类。) |
_Unset
|
coerce_numbers_to_str
|
bool | None
|
是否启用将任何 |
_Unset
|
strict
|
bool | None
|
如果为 |
_Unset
|
gt
|
SupportsGt | None
|
大于。如果设置,则值必须大于此值。仅适用于数字。 |
_Unset
|
ge
|
SupportsGe | None
|
大于或等于。如果设置,则值必须大于或等于此值。仅适用于数字。 |
_Unset
|
lt
|
SupportsLt | None
|
小于。如果设置,则值必须小于此值。仅适用于数字。 |
_Unset
|
le
|
SupportsLe | None
|
小于或等于。如果设置,则值必须小于或等于此值。仅适用于数字。 |
_Unset
|
multiple_of
|
float | None
|
值必须是此值的倍数。仅适用于数字。 |
_Unset
|
min_length
|
int | None
|
可迭代对象的最小长度。 |
_Unset
|
max_length
|
int | None
|
可迭代对象的最大长度。 |
_Unset
|
pattern
|
str | Pattern[str] | None
|
字符串的模式(正则表达式)。 |
_Unset
|
allow_inf_nan
|
bool | None
|
允许 |
_Unset
|
max_digits
|
int | None
|
字符串允许的最大位数。 |
_Unset
|
decimal_places
|
int | None
|
数字允许的最大小数位数。 |
_Unset
|
union_mode
|
Literal['smart', 'left_to_right']
|
验证联合类型时应用的策略。可以是 |
_Unset
|
fail_fast
|
bool | None
|
如果为 |
_Unset
|
extra
|
Unpack[_EmptyKwargs]
|
(已弃用)将包含在 JSON schema 中的额外字段。 警告
|
{}
|
返回
类型 | 描述 |
---|---|
Any
|
一个新的 |
源代码位于 pydantic/fields.py
933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 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 1004 1005 1006 1007 1008 1009 1010 1011 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 |
|
FieldInfo ¶
FieldInfo(**kwargs: Unpack[_FieldInfoInputs])
基类:Representation
此类保存关于字段的信息。
FieldInfo
用于任何字段定义,无论是否显式使用 Field()
函数。
警告
通常不应直接创建 FieldInfo
,您只需要在访问 BaseModel
的 .model_fields
内部结构时使用它。
属性
名称 | 类型 | 描述 |
---|---|---|
annotation |
type[Any] | None
|
字段的类型注解。 |
default |
Any
|
字段的默认值。 |
default_factory |
Callable[[], Any] | Callable[[dict[str, Any]], Any] | None
|
用于生成默认值的可调用对象。该可调用对象可以接受 0 个参数(在这种情况下,它会被直接调用)或单个参数,其中包含已验证的数据。 |
alias |
str | None
|
字段的别名。 |
alias_priority |
int | None
|
字段别名的优先级。 |
validation_alias |
str | AliasPath | AliasChoices | None
|
字段的验证别名。 |
serialization_alias |
str | None
|
字段的序列化别名。 |
title |
str | None
|
字段的标题。 |
field_title_generator |
Callable[[str, FieldInfo], str] | None
|
一个可调用对象,接受字段名称并返回其标题。 |
description |
str | None
|
字段的描述。 |
examples |
list[Any] | None
|
字段的示例列表。 |
exclude |
bool | None
|
是否从模型序列化中排除该字段。 |
discriminator |
str | Discriminator | None
|
用于区分标记联合类型的字段名称或 Discriminator。 |
deprecated |
Deprecated | str | bool | None
|
弃用消息、 |
json_schema_extra |
JsonDict | Callable[[JsonDict], None] | None
|
用于提供额外 JSON schema 属性的字典或可调用对象。 |
frozen |
bool | None
|
字段是否为冻结状态。 |
validate_default |
bool | None
|
是否验证字段的默认值。 |
repr |
bool
|
是否在模型的表示中包含该字段。 |
init |
bool | None
|
字段是否应包含在数据类的构造函数中。 |
init_var |
bool | None
|
字段是否应该仅包含在数据类的构造函数中,而不存储。 |
kw_only |
bool | None
|
字段是否应为数据类构造函数中的仅关键字参数。 |
metadata |
list[Any]
|
元数据约束列表。 |
有关预期参数的更多详细信息,请参阅 pydantic.fields.Field
的签名。
源代码位于 pydantic/fields.py
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 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 |
|
from_field staticmethod
¶
使用 Field
函数创建一个新的 FieldInfo
对象。
参数
名称 | 类型 | 描述 | 默认值 |
---|---|---|---|
default
|
Any
|
字段的默认值。默认为 Undefined。 |
PydanticUndefined
|
**kwargs
|
Unpack[_FromFieldInfoInputs]
|
额外的参数字典。 |
{}
|
引发
类型 | 描述 |
---|---|
TypeError
|
如果 'annotation' 作为关键字参数传递。 |
返回
类型 | 描述 |
---|---|
FieldInfo
|
一个具有给定参数的新 FieldInfo 对象。 |
示例
以下是如何创建具有默认值的字段,如下所示
import pydantic
class MyModel(pydantic.BaseModel):
foo: int = pydantic.Field(4)
源代码位于 pydantic/fields.py
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 |
|
from_annotation staticmethod
¶
从裸注解创建 FieldInfo
实例。
此函数在内部用于从裸注解创建 FieldInfo
,如下所示
import pydantic
class MyModel(pydantic.BaseModel):
foo: int # <-- like this
我们还考虑了注解可以是 Annotated
实例的情况,以及 Annotated
中(非第一个)参数之一是 FieldInfo
实例的情况,例如
from typing import Annotated
import annotated_types
import pydantic
class MyModel(pydantic.BaseModel):
foo: Annotated[int, annotated_types.Gt(42)]
bar: Annotated[int, pydantic.Field(gt=42)]
参数
名称 | 类型 | 描述 | 默认值 |
---|---|---|---|
annotation
|
type[Any]
|
一个注解对象。 |
required |
返回
类型 | 描述 |
---|---|
FieldInfo
|
字段元数据的实例。 |
源代码位于 pydantic/fields.py
290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 |
|
from_annotated_attribute staticmethod
¶
from_annotated_attribute(
annotation: type[Any],
default: Any,
*,
_source: AnnotationSource = ANY
) -> FieldInfo
从带有默认值的注解创建 FieldInfo
。
这用于以下情况
from typing import Annotated
import annotated_types
import pydantic
class MyModel(pydantic.BaseModel):
foo: int = 4 # <-- like this
bar: Annotated[int, annotated_types.Gt(4)] = 4 # <-- or this
spam: Annotated[int, pydantic.Field(gt=4)] = 4 # <-- or this
参数
名称 | 类型 | 描述 | 默认值 |
---|---|---|---|
annotation
|
type[Any]
|
字段的类型注解。 |
required |
default
|
Any
|
字段的默认值。 |
required |
返回
类型 | 描述 |
---|---|
FieldInfo
|
一个具有传递值的字段对象。 |
源代码位于 pydantic/fields.py
367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 |
|
merge_field_infos staticmethod
¶
合并 FieldInfo
实例,仅保留显式设置的属性。
后面的 FieldInfo
实例会覆盖前面的实例。
返回
名称 | 类型 | 描述 |
---|---|---|
FieldInfo |
FieldInfo
|
一个合并的 FieldInfo 实例。 |
源代码位于 pydantic/fields.py
470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 |
|
default_factory_takes_validated_data property
¶
default_factory_takes_validated_data: bool | None
提供的默认工厂可调用对象是否具有已验证的数据参数。
如果未设置默认工厂,则返回 None
。
get_default ¶
get_default(
*,
call_default_factory: bool = False,
validated_data: dict[str, Any] | None = None
) -> Any
获取默认值。
我们公开了一个选项,用于是否调用 default_factory(如果存在),因为调用它可能会导致我们想要避免的副作用。但是,在某些情况下,确实应该调用它(即,当通过 model_construct
实例化模型时)。
参数
名称 | 类型 | 描述 | 默认值 |
---|---|---|---|
call_default_factory
|
bool
|
是否调用默认工厂。 |
False
|
validated_data
|
dict[str, Any] | None
|
要传递给默认工厂的已验证数据。 |
None
|
返回
类型 | 描述 |
---|---|
Any
|
默认值,如果请求或未设置则调用默认工厂,否则为 |
源代码位于 pydantic/fields.py
617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 |
|
is_required ¶
is_required() -> bool
检查字段是否为必需字段(即,没有默认值或工厂)。
返回
类型 | 描述 |
---|---|
bool
|
如果字段是必需的,则返回 |
源代码位于 pydantic/fields.py
647 648 649 650 651 652 653 |
|
rebuild_annotation ¶
rebuild_annotation() -> Any
尝试重建原始注解,以便在函数签名中使用。
如果存在元数据,它会使用 Annotated
将其添加到原始注解中。否则,它会按原样返回原始注解。
请注意,由于元数据已展平,原始注解可能无法完全按最初提供的方式重建,例如,如果原始类型具有无法识别的注解,或者使用对 pydantic.Field
的调用进行注解。
返回
类型 | 描述 |
---|---|
Any
|
重建的注解。 |
源代码位于 pydantic/fields.py
655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 |
|
apply_typevars_map ¶
apply_typevars_map(
typevars_map: Mapping[TypeVar, Any] | None,
globalns: GlobalsNamespace | None = None,
localns: MappingNamespace | None = None,
) -> None
将 typevars_map
应用于注解。
此方法在分析参数化泛型类型时使用,以将类型变量替换为其具体类型。
此方法将 typevars_map
就地应用于注解。
参数
名称 | 类型 | 描述 | 默认值 |
---|---|---|---|
typevars_map
|
Mapping[TypeVar, Any] | None
|
一个字典,将类型变量映射到它们的具体类型。 |
required |
globalns
|
GlobalsNamespace | None
|
在类型注解评估期间要使用的全局命名空间。 |
None
|
localns
|
MappingNamespace | None
|
在类型注解评估期间要使用的局部命名空间。 |
None
|
另请参阅
pydantic._internal._generics.replace_types 用于将类型变量替换为其具体类型。
源代码位于 pydantic/fields.py
674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 |
|
PrivateAttr ¶
PrivateAttr(
default: _T, *, init: Literal[False] = False
) -> _T
PrivateAttr(
default: Any = PydanticUndefined,
*,
default_factory: Callable[[], Any] | None = None,
init: Literal[False] = False
) -> Any
用法文档
指示属性旨在私有使用,并且在正常验证/序列化期间不处理。
私有属性不由 Pydantic 验证,因此由您负责确保它们以类型安全的方式使用。
私有属性存储在模型上的 __private_attributes__
中。
参数
名称 | 类型 | 描述 | 默认值 |
---|---|---|---|
default
|
Any
|
属性的默认值。默认为 Undefined。 |
PydanticUndefined
|
default_factory
|
Callable[[], Any] | None
|
当需要此属性的默认值时将调用的可调用对象。如果同时设置了 |
None
|
init
|
Literal[False]
|
属性是否应包含在数据类的构造函数中。始终为 |
False
|
返回
类型 | 描述 |
---|---|
Any
|
类 |
引发
类型 | 描述 |
---|---|
ValueError
|
如果同时设置了 |
源代码位于 pydantic/fields.py
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 |
|
ModelPrivateAttr ¶
ModelPrivateAttr(
default: Any = PydanticUndefined,
*,
default_factory: Callable[[], Any] | None = None
)
基类:Representation
类模型中私有属性的描述符。
警告
通常不应直接创建 ModelPrivateAttr
实例,而应使用 pydantic.fields.PrivateAttr
。(这类似于 FieldInfo
与 Field
。)
属性
名称 | 类型 | 描述 |
---|---|---|
default |
如果未提供属性的默认值。 |
|
default_factory |
一个可调用函数,用于生成属性的默认值(如果未提供)。 |
源代码位于 pydantic/fields.py
1160 1161 1162 1163 1164 1165 1166 1167 |
|
get_default ¶
get_default() -> Any
检索对象的默认值。
如果 self.default_factory
为 None
,则该方法将返回 self.default
对象的深拷贝。
如果 self.default_factory
不为 None
,它将调用 self.default_factory
并返回返回的值。
返回
类型 | 描述 |
---|---|
Any
|
对象的默认值。 |
源代码位于 pydantic/fields.py
1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 |
|
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]
用法文档
装饰器,用于在序列化模型或数据类时包含 property
和 cached_property
。
这对于从其他字段计算的字段,或对于计算成本高昂且应缓存的字段非常有用。
from pydantic import BaseModel, computed_field
class Rectangle(BaseModel):
width: int
length: int
@computed_field
@property
def area(self) -> int:
return self.width * self.length
print(Rectangle(width=3, length=2).model_dump())
#> {'width': 3, 'length': 2, 'area': 6}
如果应用于尚未用 @property
或 @cached_property
装饰的函数,则该函数将自动用 property
包装。虽然这更简洁,但您将在 IDE 中丢失 IntelliSense,并使静态类型检查器感到困惑,因此建议显式使用 @property
。
Mypy 警告
即使在 @computed_field
之前将 @property
或 @cached_property
应用于您的函数,mypy 也可能抛出 Decorated property not supported
错误。有关更多信息,请参阅 mypy issue #1362。要避免此错误消息,请在 @computed_field
行中添加 # type: ignore[prop-decorator]
。
pyright 支持 @computed_field
,不会出现错误。
import random
from pydantic import BaseModel, computed_field
class Square(BaseModel):
width: float
@computed_field
def area(self) -> float: # converted to a `property` by `computed_field`
return round(self.width**2, 2)
@area.setter
def area(self, new_area: float) -> None:
self.width = new_area**0.5
@computed_field(alias='the magic number', repr=False)
def random_number(self) -> int:
return random.randint(0, 1_000)
square = Square(width=1.3)
# `random_number` does not appear in representation
print(repr(square))
#> Square(width=1.3, area=1.69)
print(square.random_number)
#> 3
square.area = 4
print(square.model_dump_json(by_alias=True))
#> {"width":2.0,"area":4.0,"the magic number":3}
使用 computed_field
覆盖
您不能使用子类中的 computed_field
覆盖父类中的字段。如果允许这样做,mypy
会对此行为发出警告,并且 dataclasses
也不允许这种模式。请参阅以下示例
from pydantic import BaseModel, computed_field
class Parent(BaseModel):
a: str
try:
class Child(Parent):
@computed_field
@property
def a(self) -> str:
return 'new a'
except TypeError as e:
print(e)
'''
Field 'a' of class 'Child' overrides symbol of same name in a parent class. This override with a computed_field is incompatible.
'''
默认情况下,用 @computed_field
装饰的私有属性具有 repr=False
。
from functools import cached_property
from pydantic import BaseModel, computed_field
class Model(BaseModel):
foo: int
@computed_field
@cached_property
def _private_cached_property(self) -> int:
return -self.foo
@computed_field
@property
def _private_property(self) -> int:
return -self.foo
m = Model(foo=1)
print(repr(m))
#> Model(foo=1)
参数
名称 | 类型 | 描述 | 默认值 |
---|---|---|---|
func
|
PropertyT | None
|
要包装的函数。 |
None
|
alias
|
str | None
|
当序列化此计算字段时要使用的别名,仅当 |
None
|
alias_priority
|
int | None
|
别名的优先级。这会影响是否使用别名生成器 |
None
|
title
|
str | None
|
在 JSON Schema 中包含此计算字段时要使用的标题 |
None
|
field_title_generator
|
Callable[[str, ComputedFieldInfo], str] | None
|
一个可调用对象,接受字段名称并返回其标题。 |
None
|
description
|
str | None
|
在 JSON Schema 中包含此计算字段时要使用的描述,默认为函数的文档字符串 |
None
|
deprecated
|
Deprecated | str | bool | None
|
弃用消息(或 |
None
|
examples
|
list[Any] | None
|
在 JSON Schema 中包含此计算字段时要使用的示例值 |
None
|
json_schema_extra
|
JsonDict | Callable[[JsonDict], None] | None
|
用于提供额外 JSON schema 属性的字典或可调用对象。 |
None
|
repr
|
bool | None
|
是否在模型 repr 中包含此计算字段。私有属性的默认值为 |
None
|
return_type
|
Any
|
序列化为 JSON 时序列化逻辑要期望的可选返回类型,如果包含此项,则必须正确,否则会引发 |
PydanticUndefined
|
返回
类型 | 描述 |
---|---|
PropertyT | Callable[[PropertyT], PropertyT]
|
属性的代理包装器。 |
源代码位于 pydantic/fields.py
1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 |
|
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,
)
用于存储来自 @computed_field
的数据,以便在构建 pydantic-core schema 时可以访问它。
属性
名称 | 类型 | 描述 |
---|---|---|
decorator_repr |
str
|
表示装饰器字符串 '@computed_field' 的类变量。 |
wrapped_property |
property
|
包装的计算字段属性。 |
return_type |
Any
|
计算字段属性的返回值的类型。 |
alias |
str | None
|
序列化期间要使用的属性别名。 |
alias_priority |
int | None
|
别名的优先级。这会影响是否使用别名生成器。 |
title |
str | None
|
要包含在序列化 JSON schema 中的计算字段的标题。 |
field_title_generator |
Callable[[str, ComputedFieldInfo], str] | None
|
一个可调用对象,接受字段名称并返回其标题。 |
description |
str | None
|
要包含在序列化 JSON schema 中的计算字段的描述。 |
deprecated |
Deprecated | str | bool | None
|
弃用消息、 |
examples |
list[Any] | None
|
要包含在序列化 JSON schema 中的计算字段的示例值。 |
json_schema_extra |
JsonDict | Callable[[JsonDict], None] | None
|
用于提供额外 JSON schema 属性的字典或可调用对象。 |
repr |
bool
|
一个布尔值,指示是否在 repr 输出中包含该字段。 |