Create `FieldInfo` from an annotation with a default value. This is used in cases like the following: ```python from typing import Annotated import annotated_types import pydantic class MyModel(pydantic.BaseModel): foo: int = 4 # <--
(
annotation: type[Any], default: Any, *, _source: AnnotationSource = AnnotationSource.ANY
)
| 377 | |
| 378 | @staticmethod |
| 379 | def from_annotated_attribute( |
| 380 | annotation: type[Any], default: Any, *, _source: AnnotationSource = AnnotationSource.ANY |
| 381 | ) -> FieldInfo: |
| 382 | """Create `FieldInfo` from an annotation with a default value. |
| 383 | |
| 384 | This is used in cases like the following: |
| 385 | |
| 386 | ```python |
| 387 | from typing import Annotated |
| 388 | |
| 389 | import annotated_types |
| 390 | |
| 391 | import pydantic |
| 392 | |
| 393 | class MyModel(pydantic.BaseModel): |
| 394 | foo: int = 4 # <-- like this |
| 395 | bar: Annotated[int, annotated_types.Gt(4)] = 4 # <-- or this |
| 396 | spam: Annotated[int, pydantic.Field(gt=4)] = 4 # <-- or this |
| 397 | ``` |
| 398 | |
| 399 | Args: |
| 400 | annotation: The type annotation of the field. |
| 401 | default: The default value of the field. |
| 402 | |
| 403 | Returns: |
| 404 | A field object with the passed values. |
| 405 | """ |
| 406 | if annotation is not MISSING and annotation is default: |
| 407 | raise PydanticUserError( |
| 408 | 'Error when building FieldInfo from annotated attribute. ' |
| 409 | "Make sure you don't have any field name clashing with a type annotation.", |
| 410 | code='unevaluable-type-annotation', |
| 411 | ) |
| 412 | |
| 413 | try: |
| 414 | inspected_ann = inspect_annotation( |
| 415 | annotation, |
| 416 | annotation_source=_source, |
| 417 | unpack_type_aliases='skip', |
| 418 | ) |
| 419 | except ForbiddenQualifier as e: |
| 420 | raise PydanticForbiddenQualifier(e.qualifier, annotation) |
| 421 | |
| 422 | # TODO check for classvar and error? |
| 423 | |
| 424 | # TODO infer from the default, this can be done in v3 once we treat final fields with |
| 425 | # a default as proper fields and not class variables: |
| 426 | type_expr: Any = Any if inspected_ann.type is UNKNOWN else inspected_ann.type |
| 427 | final = 'final' in inspected_ann.qualifiers |
| 428 | metadata = inspected_ann.metadata |
| 429 | |
| 430 | # HACK 1: the order in which the metadata is merged is inconsistent; we need to prepend |
| 431 | # metadata from the assignment at the beginning of the metadata. Changing this is only |
| 432 | # possible in v3 (at least). See https://github.com/pydantic/pydantic/issues/10507 |
| 433 | prepend_metadata: list[Any] | None = None |
| 434 | attr_overrides = {'annotation': type_expr} |
| 435 | if final: |
| 436 | attr_overrides['frozen'] = True |
no test coverage detected