MCPcopy
hub / github.com/pydantic/pydantic / from_annotation

Method from_annotation

pydantic/fields.py:319–376  ·  view source on GitHub ↗

Creates a `FieldInfo` instance from a bare annotation. This function is used internally to create a `FieldInfo` from a bare annotation like this: ```python import pydantic class MyModel(pydantic.BaseModel): foo: int # <-- like this ```

(annotation: type[Any], *, _source: AnnotationSource = AnnotationSource.ANY)

Source from the content-addressed store, hash-verified

317
318 @staticmethod
319 def from_annotation(annotation: type[Any], *, _source: AnnotationSource = AnnotationSource.ANY) -> FieldInfo:
320 """Creates a `FieldInfo` instance from a bare annotation.
321
322 This function is used internally to create a `FieldInfo` from a bare annotation like this:
323
324 ```python
325 import pydantic
326
327 class MyModel(pydantic.BaseModel):
328 foo: int # <-- like this
329 ```
330
331 We also account for the case where the annotation can be an instance of `Annotated` and where
332 one of the (not first) arguments in `Annotated` is an instance of `FieldInfo`, e.g.:
333
334 ```python
335 from typing import Annotated
336
337 import annotated_types
338
339 import pydantic
340
341 class MyModel(pydantic.BaseModel):
342 foo: Annotated[int, annotated_types.Gt(42)]
343 bar: Annotated[int, pydantic.Field(gt=42)]
344 ```
345
346 Args:
347 annotation: An annotation object.
348
349 Returns:
350 An instance of the field metadata.
351 """
352 try:
353 inspected_ann = inspect_annotation(
354 annotation,
355 annotation_source=_source,
356 unpack_type_aliases='skip',
357 )
358 except ForbiddenQualifier as e:
359 raise PydanticForbiddenQualifier(e.qualifier, annotation)
360
361 # TODO check for classvar and error?
362
363 # No assigned value, this happens when using a bare `Final` qualifier (also for other
364 # qualifiers, but they shouldn't appear here). In this case we infer the type as `Any`
365 # because we don't have any assigned value.
366 type_expr: Any = Any if inspected_ann.type is UNKNOWN else inspected_ann.type
367 final = 'final' in inspected_ann.qualifiers
368 metadata = inspected_ann.metadata
369
370 attr_overrides = {'annotation': type_expr}
371 if final:
372 attr_overrides['frozen'] = True
373 field_info = FieldInfo._construct(metadata, **attr_overrides)
374 field_info._qualifiers = inspected_ann.qualifiers
375 field_info._final = True
376 return field_info

Calls 2

_constructMethod · 0.80