Coverage for pydantic / _internal / _core_utils.py: 100.00%
28 statements
« prev ^ index » next coverage.py v7.13.5, created at 2026-11-21 11:56 +0000
« prev ^ index » next coverage.py v7.13.5, created at 2026-11-21 11:56 +0000
1from __future__ import annotations 1gabhijkcdlmnsoefpqr
3import inspect 1gabhijkcdlmnsoefpqr
4from collections.abc import Mapping, Sequence 1gabhijkcdlmnsoefpqr
5from typing import TYPE_CHECKING, Any, TypeAlias, TypeGuard 1gabhijkcdlmnsoefpqr
7from pydantic_core import CoreSchema, core_schema 1gabhijkcdlmnsoefpqr
9if TYPE_CHECKING: 1gabhijkcdlmnsoefpqr
10 from rich.console import Console
12AnyFunctionSchema: TypeAlias = ( 1gabhijkcdlmnsoefpqr
13 core_schema.AfterValidatorFunctionSchema
14 | core_schema.BeforeValidatorFunctionSchema
15 | core_schema.WrapValidatorFunctionSchema
16 | core_schema.PlainValidatorFunctionSchema
17)
20FunctionSchemaWithInnerSchema: TypeAlias = ( 1gabhijkcdlmnsoefpqr
21 core_schema.AfterValidatorFunctionSchema
22 | core_schema.BeforeValidatorFunctionSchema
23 | core_schema.WrapValidatorFunctionSchema
24)
27CoreSchemaField: TypeAlias = ( 1gabhijkcdlmnsoefpqr
28 core_schema.ModelField | core_schema.DataclassField | core_schema.TypedDictField | core_schema.ComputedField
29)
31CoreSchemaOrField: TypeAlias = core_schema.CoreSchema | CoreSchemaField 1gabhijkcdlmnsoefpqr
33_CORE_SCHEMA_FIELD_TYPES = {'typed-dict-field', 'dataclass-field', 'model-field', 'computed-field'} 1gabhijkcdlmnsoefpqr
34_FUNCTION_WITH_INNER_SCHEMA_TYPES = {'function-before', 'function-after', 'function-wrap'} 1gabhijkcdlmnsoefpqr
37def is_core_schema( 1gabhijkcdlmnsoefpqr
38 schema: CoreSchemaOrField,
39) -> TypeGuard[CoreSchema]:
40 return schema['type'] not in _CORE_SCHEMA_FIELD_TYPES 1gabhijkcdlmnoefpqr
43def is_core_schema_field( 1gabhijkcdlmnsoefpqr
44 schema: CoreSchemaOrField,
45) -> TypeGuard[CoreSchemaField]:
46 return schema['type'] in _CORE_SCHEMA_FIELD_TYPES 1gabhijkcdlmnoefpqr
49def is_function_with_inner_schema( 1gabhijkcdlmnsoefpqr
50 schema: CoreSchemaOrField,
51) -> TypeGuard[FunctionSchemaWithInnerSchema]:
52 return schema['type'] in _FUNCTION_WITH_INNER_SCHEMA_TYPES 1gabhijkcdlmnoefpqr
55def as_ser_schema(schema: CoreSchema) -> core_schema.SerSchema: 1gabhijkcdlmnsoefpqr
56 """Return a schema suitable for the `'serialization'` key of a core schema, from an arbitrary core schema.
58 Any core schema can be used as a serialization schema, except `'function-plain'` and `'function-wrap'`
59 schemas, as these types are already used by the plain and wrap serializer *function* schemas.
60 For these, mimic what pydantic-core would do if they were used as the *main* schema:
62 - if the function schema has a `'serialization'` schema, use it.
63 - otherwise, a `'function-plain'` schema is serialized as `'any'`, and a `'function-wrap'` schema
64 is serialized using its inner schema.
66 Note that `schema` is expected to be a *core* schema (e.g. as returned by the schema generator),
67 not an existing `'serialization'` schema.
68 """
69 if schema['type'] == 'function-plain' or schema['type'] == 'function-wrap': 1gabhijkcdlmnoefpqr
70 if (ser_schema := schema.get('serialization')) is not None: 1gabhijkcdlmnoefpqr
71 return ser_schema 1gabhijkcdlmnoefpqr
72 if schema['type'] == 'function-plain': 1gabhijkcdlmnoefpqr
73 return core_schema.any_schema() 1gabhijkcdlmnoefpqr
74 return as_ser_schema(schema['schema']) 1gabhijkcdlmnoefpqr
75 return schema 1gabhijkcdlmnoefpqr
78def get_ref(s: core_schema.CoreSchema) -> None | str: 1gabhijkcdlmnsoefpqr
79 """Get the ref from the schema if it has one.
80 This exists just for type checking to work correctly.
81 """
82 return s.get('ref', None) 1gabhijkcdlmnsoefpqr
85def _clean_schema_for_pretty_print(obj: Any, strip_metadata: bool = True) -> Any: # pragma: no cover 1gabhijkcdlmnsoefpqr
86 """A utility function to remove irrelevant information from a core schema."""
87 if isinstance(obj, Mapping):
88 new_dct = {}
89 for k, v in obj.items():
90 if k == 'metadata' and strip_metadata:
91 new_metadata = {}
93 for meta_k, meta_v in v.items():
94 if meta_k in ('pydantic_js_functions', 'pydantic_js_annotation_functions'):
95 new_metadata['js_metadata'] = '<stripped>'
96 else:
97 new_metadata[meta_k] = _clean_schema_for_pretty_print(meta_v, strip_metadata=strip_metadata)
99 if list(new_metadata.keys()) == ['js_metadata']:
100 new_metadata = {'<stripped>'}
102 new_dct[k] = new_metadata
103 # Remove some defaults:
104 elif k in ('custom_init', 'root_model') and not v:
105 continue
106 else:
107 new_dct[k] = _clean_schema_for_pretty_print(v, strip_metadata=strip_metadata)
109 return new_dct
110 elif isinstance(obj, Sequence) and not isinstance(obj, str):
111 return [_clean_schema_for_pretty_print(v, strip_metadata=strip_metadata) for v in obj]
112 else:
113 return obj
116def pretty_print_core_schema( 1gabhijkcdlmnsoefpqr
117 val: Any, 1abcdsef
118 *,
119 console: Console | None = None, 1gabhijkcdlmnsoefpqr
120 max_depth: int | None = None, 1gabhijkcdlmnsoefpqr
121 strip_metadata: bool = True, 1gabhijkcdlmnsoefpqr
122) -> None: # pragma: no cover 1abcdsef
123 """Pretty-print a core schema using the `rich` library.
125 Args:
126 val: The core schema to print, or a Pydantic model/dataclass/type adapter
127 (in which case the cached core schema is fetched and printed).
128 console: A rich console to use when printing. Defaults to the global rich console instance.
129 max_depth: The number of nesting levels which may be printed.
130 strip_metadata: Whether to strip metadata in the output. If `True` any known core metadata
131 attributes will be stripped (but custom attributes are kept). Defaults to `True`.
132 """
133 # lazy import:
134 from rich.pretty import pprint
136 # circ. imports:
137 from pydantic import BaseModel, TypeAdapter
138 from pydantic.dataclasses import is_pydantic_dataclass
140 if (inspect.isclass(val) and issubclass(val, BaseModel)) or is_pydantic_dataclass(val):
141 val = val.__pydantic_core_schema__
142 if isinstance(val, TypeAdapter):
143 val = val.core_schema
144 cleaned_schema = _clean_schema_for_pretty_print(val, strip_metadata=strip_metadata)
146 pprint(cleaned_schema, console=console, max_depth=max_depth)
149pps = pretty_print_core_schema 1gabhijkcdlmnsoefpqr