MCPcopy
hub / github.com/pydantic/pydantic / from_annotated_attribute

Method from_annotated_attribute

pydantic/fields.py:379–477  ·  view source on GitHub ↗

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
    )

Source from the content-addressed store, hash-verified

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

Callers 6

collect_model_fieldsFunction · 0.80
_recreate_field_infoFunction · 0.80
collect_dataclass_fieldsFunction · 0.80
rebuild_dataclass_fieldsFunction · 0.80

Calls 7

PydanticUserErrorClass · 0.85
_copyMethod · 0.80
_from_dataclass_fieldMethod · 0.80
_constructMethod · 0.80
updateMethod · 0.45
itemsMethod · 0.45

Tested by

no test coverage detected