Coverage for pydantic/_internal/_known_annotated_metadata.py: 91.47%
147 statements
« prev ^ index » next coverage.py v7.5.4, created at 2024-07-03 19:29 +0000
« prev ^ index » next coverage.py v7.5.4, created at 2024-07-03 19:29 +0000
1from __future__ import annotations 1abcdefghijklmnopqrstuvwxyzMNOPQRSTUVABCDEFGHIJKL
3from collections import defaultdict 1abcdefghijklmnopqrstuvwxyzMNOPQRSTUVABCDEFGHIJKL
4from copy import copy 1abcdefghijklmnopqrstuvwxyzMNOPQRSTUVABCDEFGHIJKL
5from functools import lru_cache, partial 1abcdefghijklmnopqrstuvwxyzMNOPQRSTUVABCDEFGHIJKL
6from typing import TYPE_CHECKING, Any, Callable, Iterable 1abcdefghijklmnopqrstuvwxyzMNOPQRSTUVABCDEFGHIJKL
8from pydantic_core import CoreSchema, PydanticCustomError, to_jsonable_python 1abcdefghijklmnopqrstuvwxyzMNOPQRSTUVABCDEFGHIJKL
9from pydantic_core import core_schema as cs 1abcdefghijklmnopqrstuvwxyzMNOPQRSTUVABCDEFGHIJKL
11from ._fields import PydanticMetadata 1abcdefghijklmnopqrstuvwxyzMNOPQRSTUVABCDEFGHIJKL
13if TYPE_CHECKING: 1abcdefghijklmnopqrstuvwxyzMNOPQRSTUVABCDEFGHIJKL
14 from ..annotated_handlers import GetJsonSchemaHandler
16STRICT = {'strict'} 1abcdefghijklmnopqrstuvwxyzMNOPQRSTUVABCDEFGHIJKL
17FAIL_FAST = {'fail_fast'} 1abcdefghijklmnopqrstuvwxyzMNOPQRSTUVABCDEFGHIJKL
18LENGTH_CONSTRAINTS = {'min_length', 'max_length'} 1abcdefghijklmnopqrstuvwxyzMNOPQRSTUVABCDEFGHIJKL
19INEQUALITY = {'le', 'ge', 'lt', 'gt'} 1abcdefghijklmnopqrstuvwxyzMNOPQRSTUVABCDEFGHIJKL
20NUMERIC_CONSTRAINTS = {'multiple_of', *INEQUALITY} 1abcdefghijklmnopqrstuvwxyzMNOPQRSTUVABCDEFGHIJKL
21ALLOW_INF_NAN = {'allow_inf_nan'} 1abcdefghijklmnopqrstuvwxyzMNOPQRSTUVABCDEFGHIJKL
23STR_CONSTRAINTS = { 1abcdefghijklmnopqrstuvwxyzMNOPQRSTUVABCDEFGHIJKL
24 *LENGTH_CONSTRAINTS,
25 *STRICT,
26 'strip_whitespace',
27 'to_lower',
28 'to_upper',
29 'pattern',
30 'coerce_numbers_to_str',
31}
32BYTES_CONSTRAINTS = {*LENGTH_CONSTRAINTS, *STRICT} 1abcdefghijklmnopqrstuvwxyzMNOPQRSTUVABCDEFGHIJKL
34LIST_CONSTRAINTS = {*LENGTH_CONSTRAINTS, *STRICT, *FAIL_FAST} 1abcdefghijklmnopqrstuvwxyzMNOPQRSTUVABCDEFGHIJKL
35TUPLE_CONSTRAINTS = {*LENGTH_CONSTRAINTS, *STRICT, *FAIL_FAST} 1abcdefghijklmnopqrstuvwxyzMNOPQRSTUVABCDEFGHIJKL
36SET_CONSTRAINTS = {*LENGTH_CONSTRAINTS, *STRICT, *FAIL_FAST} 1abcdefghijklmnopqrstuvwxyzMNOPQRSTUVABCDEFGHIJKL
37DICT_CONSTRAINTS = {*LENGTH_CONSTRAINTS, *STRICT} 1abcdefghijklmnopqrstuvwxyzMNOPQRSTUVABCDEFGHIJKL
38GENERATOR_CONSTRAINTS = {*LENGTH_CONSTRAINTS, *STRICT} 1abcdefghijklmnopqrstuvwxyzMNOPQRSTUVABCDEFGHIJKL
39SEQUENCE_CONSTRAINTS = {*LENGTH_CONSTRAINTS, *FAIL_FAST} 1abcdefghijklmnopqrstuvwxyzMNOPQRSTUVABCDEFGHIJKL
41FLOAT_CONSTRAINTS = {*NUMERIC_CONSTRAINTS, *ALLOW_INF_NAN, *STRICT} 1abcdefghijklmnopqrstuvwxyzMNOPQRSTUVABCDEFGHIJKL
42DECIMAL_CONSTRAINTS = {'max_digits', 'decimal_places', *FLOAT_CONSTRAINTS} 1abcdefghijklmnopqrstuvwxyzMNOPQRSTUVABCDEFGHIJKL
43INT_CONSTRAINTS = {*NUMERIC_CONSTRAINTS, *ALLOW_INF_NAN, *STRICT} 1abcdefghijklmnopqrstuvwxyzMNOPQRSTUVABCDEFGHIJKL
44BOOL_CONSTRAINTS = STRICT 1abcdefghijklmnopqrstuvwxyzMNOPQRSTUVABCDEFGHIJKL
45UUID_CONSTRAINTS = STRICT 1abcdefghijklmnopqrstuvwxyzMNOPQRSTUVABCDEFGHIJKL
47DATE_TIME_CONSTRAINTS = {*NUMERIC_CONSTRAINTS, *STRICT} 1abcdefghijklmnopqrstuvwxyzMNOPQRSTUVABCDEFGHIJKL
48TIMEDELTA_CONSTRAINTS = {*NUMERIC_CONSTRAINTS, *STRICT} 1abcdefghijklmnopqrstuvwxyzMNOPQRSTUVABCDEFGHIJKL
49TIME_CONSTRAINTS = {*NUMERIC_CONSTRAINTS, *STRICT} 1abcdefghijklmnopqrstuvwxyzMNOPQRSTUVABCDEFGHIJKL
50LAX_OR_STRICT_CONSTRAINTS = STRICT 1abcdefghijklmnopqrstuvwxyzMNOPQRSTUVABCDEFGHIJKL
51ENUM_CONSTRAINTS = STRICT 1abcdefghijklmnopqrstuvwxyzMNOPQRSTUVABCDEFGHIJKL
53UNION_CONSTRAINTS = {'union_mode'} 1abcdefghijklmnopqrstuvwxyzMNOPQRSTUVABCDEFGHIJKL
54URL_CONSTRAINTS = { 1abcdefghijklmnopqrstuvwxyzMNOPQRSTUVABCDEFGHIJKL
55 'max_length',
56 'allowed_schemes',
57 'host_required',
58 'default_host',
59 'default_port',
60 'default_path',
61}
63TEXT_SCHEMA_TYPES = ('str', 'bytes', 'url', 'multi-host-url') 1abcdefghijklmnopqrstuvwxyzMNOPQRSTUVABCDEFGHIJKL
64SEQUENCE_SCHEMA_TYPES = ('list', 'tuple', 'set', 'frozenset', 'generator', *TEXT_SCHEMA_TYPES) 1abcdefghijklmnopqrstuvwxyzMNOPQRSTUVABCDEFGHIJKL
65NUMERIC_SCHEMA_TYPES = ('float', 'int', 'date', 'time', 'timedelta', 'datetime') 1abcdefghijklmnopqrstuvwxyzMNOPQRSTUVABCDEFGHIJKL
67CONSTRAINTS_TO_ALLOWED_SCHEMAS: dict[str, set[str]] = defaultdict(set) 1abcdefghijklmnopqrstuvwxyzMNOPQRSTUVABCDEFGHIJKL
69constraint_schema_pairings: list[tuple[set[str], tuple[str, ...]]] = [ 1abcdefghijklmnopqrstuvwxyzMNOPQRSTUVABCDEFGHIJKL
70 (STR_CONSTRAINTS, TEXT_SCHEMA_TYPES),
71 (BYTES_CONSTRAINTS, ('bytes',)),
72 (LIST_CONSTRAINTS, ('list',)),
73 (TUPLE_CONSTRAINTS, ('tuple',)),
74 (SET_CONSTRAINTS, ('set', 'frozenset')),
75 (DICT_CONSTRAINTS, ('dict',)),
76 (GENERATOR_CONSTRAINTS, ('generator',)),
77 (FLOAT_CONSTRAINTS, ('float',)),
78 (INT_CONSTRAINTS, ('int',)),
79 (DATE_TIME_CONSTRAINTS, ('date', 'time', 'datetime')),
80 (TIMEDELTA_CONSTRAINTS, ('timedelta',)),
81 (TIME_CONSTRAINTS, ('time',)),
82 # TODO: this is a bit redundant, we could probably avoid some of these
83 (STRICT, (*TEXT_SCHEMA_TYPES, *SEQUENCE_SCHEMA_TYPES, *NUMERIC_SCHEMA_TYPES, 'typed-dict', 'model')),
84 (UNION_CONSTRAINTS, ('union',)),
85 (URL_CONSTRAINTS, ('url', 'multi-host-url')),
86 (BOOL_CONSTRAINTS, ('bool',)),
87 (UUID_CONSTRAINTS, ('uuid',)),
88 (LAX_OR_STRICT_CONSTRAINTS, ('lax-or-strict',)),
89 (ENUM_CONSTRAINTS, ('enum',)),
90 (DECIMAL_CONSTRAINTS, ('decimal',)),
91]
93for constraints, schemas in constraint_schema_pairings: 1abcdefghijklmnopqrstuvwxyzMNOPQRSTUVABCDEFGHIJKL
94 for c in constraints: 1abcdefghijklmnopqrstuvwxyzMNOPQRSTUVABCDEFGHIJKL
95 CONSTRAINTS_TO_ALLOWED_SCHEMAS[c].update(schemas) 1abcdefghijklmnopqrstuvwxyzMNOPQRSTUVABCDEFGHIJKL
98def add_js_update_schema(s: cs.CoreSchema, f: Callable[[], dict[str, Any]]) -> None: 1abcdefghijklmnopqrstuvwxyzMNOPQRSTUVABCDEFGHIJKL
99 def update_js_schema(s: cs.CoreSchema, handler: GetJsonSchemaHandler) -> dict[str, Any]: 1abcdefghijklmnopqrstuvwxyzABCDEFGHIJKL
100 js_schema = handler(s) 1abcdefghijklmnopqrstuvwxyzABCDEFGHIJKL
101 js_schema.update(f()) 1abcdefghijklmnopqrstuvwxyzABCDEFGHIJKL
102 return js_schema 1abcdefghijklmnopqrstuvwxyzABCDEFGHIJKL
104 if 'metadata' in s: 104 ↛ 105line 104 didn't jump to line 105 because the condition on line 104 was never true1abcdefghijklmnopqrstuvwxyzABCDEFGHIJKL
105 metadata = s['metadata']
106 if 'pydantic_js_functions' in s:
107 metadata['pydantic_js_functions'].append(update_js_schema)
108 else:
109 metadata['pydantic_js_functions'] = [update_js_schema]
110 else:
111 s['metadata'] = {'pydantic_js_functions': [update_js_schema]} 1abcdefghijklmnopqrstuvwxyzABCDEFGHIJKL
114def as_jsonable_value(v: Any) -> Any: 1abcdefghijklmnopqrstuvwxyzMNOPQRSTUVABCDEFGHIJKL
115 if type(v) not in (int, str, float, bytes, bool, type(None)): 115 ↛ 116line 115 didn't jump to line 116 because the condition on line 115 was never true1abcdefghijklmnopqrstuvwxyzABCDEFGHIJKL
116 return to_jsonable_python(v)
117 return v 1abcdefghijklmnopqrstuvwxyzABCDEFGHIJKL
120def expand_grouped_metadata(annotations: Iterable[Any]) -> Iterable[Any]: 1abcdefghijklmnopqrstuvwxyzMNOPQRSTUVABCDEFGHIJKL
121 """Expand the annotations.
123 Args:
124 annotations: An iterable of annotations.
126 Returns:
127 An iterable of expanded annotations.
129 Example:
130 ```py
131 from annotated_types import Ge, Len
133 from pydantic._internal._known_annotated_metadata import expand_grouped_metadata
135 print(list(expand_grouped_metadata([Ge(4), Len(5)])))
136 #> [Ge(ge=4), MinLen(min_length=5)]
137 ```
138 """
139 import annotated_types as at 1abcdefghijklmnopqrstuvwxyzMNOPQRSTUVABCDEFGHIJKL
141 from pydantic.fields import FieldInfo # circular import 1abcdefghijklmnopqrstuvwxyzMNOPQRSTUVABCDEFGHIJKL
143 for annotation in annotations: 1abcdefghijklmnopqrstuvwxyzMNOPQRSTUVABCDEFGHIJKL
144 if isinstance(annotation, at.GroupedMetadata): 1abcdefghijklmnopqrstuvwxyzMNOPQRSTUVABCDEFGHIJKL
145 yield from annotation 1abcdefghijklmnopqrstuvwxyzABCDEFGHIJKL
146 elif isinstance(annotation, FieldInfo): 1abcdefghijklmnopqrstuvwxyzMNOPQRSTUVABCDEFGHIJKL
147 yield from annotation.metadata 1abcdefghijklmnopqrstuvwxyzABCDEFGHIJKL
148 # this is a bit problematic in that it results in duplicate metadata
149 # all of our "consumers" can handle it, but it is not ideal
150 # we probably should split up FieldInfo into:
151 # - annotated types metadata
152 # - individual metadata known only to Pydantic
153 annotation = copy(annotation) 1abcdefghijklmnopqrstuvwxyzABCDEFGHIJKL
154 annotation.metadata = [] 1abcdefghijklmnopqrstuvwxyzABCDEFGHIJKL
155 yield annotation 1abcdefghijklmnopqrstuvwxyzABCDEFGHIJKL
156 else:
157 yield annotation 1abcdefghijklmnopqrstuvwxyzMNOPQRSTUVABCDEFGHIJKL
160@lru_cache 1abcdefghijklmnopqrstuvwxyzMNOPQRSTUVABCDEFGHIJKL
161def _get_at_to_constraint_map() -> dict[type, str]: 1abcdefghijklmnopqrstuvwxyzMNOPQRSTUVABCDEFGHIJKL
162 """Return a mapping of annotated types to constraints.
164 Normally, we would define a mapping like this in the module scope, but we can't do that
165 because we don't permit module level imports of `annotated_types`, in an attempt to speed up
166 the import time of `pydantic`. We still only want to have this dictionary defined in one place,
167 so we use this function to cache the result.
168 """
169 import annotated_types as at 1abcdefghijklmnopqrstuvwxyzMNOPQRSTUVABCDEFGHIJKL
171 return { 1abcdefghijklmnopqrstuvwxyzMNOPQRSTUVABCDEFGHIJKL
172 at.Gt: 'gt',
173 at.Ge: 'ge',
174 at.Lt: 'lt',
175 at.Le: 'le',
176 at.MultipleOf: 'multiple_of',
177 at.MinLen: 'min_length',
178 at.MaxLen: 'max_length',
179 }
182def apply_known_metadata(annotation: Any, schema: CoreSchema) -> CoreSchema | None: # noqa: C901 1abcdefghijklmnopqrstuvwxyzMNOPQRSTUVABCDEFGHIJKL
183 """Apply `annotation` to `schema` if it is an annotation we know about (Gt, Le, etc.).
184 Otherwise return `None`.
186 This does not handle all known annotations. If / when it does, it can always
187 return a CoreSchema and return the unmodified schema if the annotation should be ignored.
189 Assumes that GroupedMetadata has already been expanded via `expand_grouped_metadata`.
191 Args:
192 annotation: The annotation.
193 schema: The schema.
195 Returns:
196 An updated schema with annotation if it is an annotation we know about, `None` otherwise.
198 Raises:
199 PydanticCustomError: If `Predicate` fails.
200 """
201 import annotated_types as at 1abcdefghijklmnopqrstuvwxyzMNOPQRSTUVABCDEFGHIJKL
203 from ._validators import forbid_inf_nan_check, get_constraint_validator 1abcdefghijklmnopqrstuvwxyzMNOPQRSTUVABCDEFGHIJKL
205 schema = schema.copy() 1abcdefghijklmnopqrstuvwxyzMNOPQRSTUVABCDEFGHIJKL
206 schema_update, other_metadata = collect_known_metadata([annotation]) 1abcdefghijklmnopqrstuvwxyzMNOPQRSTUVABCDEFGHIJKL
207 schema_type = schema['type'] 1abcdefghijklmnopqrstuvwxyzMNOPQRSTUVABCDEFGHIJKL
209 chain_schema_constraints: set[str] = { 1abcdefghijklmnopqrstuvwxyzMNOPQRSTUVABCDEFGHIJKL
210 'pattern',
211 'strip_whitespace',
212 'to_lower',
213 'to_upper',
214 'coerce_numbers_to_str',
215 }
216 chain_schema_steps: list[CoreSchema] = [] 1abcdefghijklmnopqrstuvwxyzMNOPQRSTUVABCDEFGHIJKL
218 for constraint, value in schema_update.items(): 1abcdefghijklmnopqrstuvwxyzMNOPQRSTUVABCDEFGHIJKL
219 if constraint not in CONSTRAINTS_TO_ALLOWED_SCHEMAS: 219 ↛ 220line 219 didn't jump to line 220 because the condition on line 219 was never true1abcdefghijklmnopqrstuvwxyzABCDEFGHIJKL
220 raise ValueError(f'Unknown constraint {constraint}')
221 allowed_schemas = CONSTRAINTS_TO_ALLOWED_SCHEMAS[constraint] 1abcdefghijklmnopqrstuvwxyzABCDEFGHIJKL
223 # if it becomes necessary to handle more than one constraint
224 # in this recursive case with function-after or function-wrap, we should refactor
225 # this is a bit challenging because we sometimes want to apply constraints to the inner schema,
226 # whereas other times we want to wrap the existing schema with a new one that enforces a new constraint.
227 if schema_type in {'function-before', 'function-wrap', 'function-after'} and constraint == 'strict': 1abcdefghijklmnopqrstuvwxyzABCDEFGHIJKL
228 schema['schema'] = apply_known_metadata(annotation, schema['schema']) # type: ignore # schema is function-after schema 1abcdefghijklmnopqrstuvwxyzABCDEFGHIJKL
229 return schema 1abcdefghijklmnopqrstuvwxyzABCDEFGHIJKL
231 if schema_type in allowed_schemas: 1abcdefghijklmnopqrstuvwxyzABCDEFGHIJKL
232 if constraint == 'union_mode' and schema_type == 'union': 1abcdefghijklmnopqrstuvwxyzABCDEFGHIJKL
233 schema['mode'] = value # type: ignore # schema is UnionSchema 1abcdefghijklmnopqrstuvwxyzABCDEFGHIJKL
234 else:
235 schema[constraint] = value 1abcdefghijklmnopqrstuvwxyzABCDEFGHIJKL
236 continue 1abcdefghijklmnopqrstuvwxyzABCDEFGHIJKL
238 if constraint in chain_schema_constraints: 1abcdefghijklmnopqrstuvwxyzABCDEFGHIJKL
239 chain_schema_steps.append(cs.str_schema(**{constraint: value})) 1abcdefghijklmnopqrstuvwxyzABCDEFGHIJKL
240 elif constraint in {*NUMERIC_CONSTRAINTS, *LENGTH_CONSTRAINTS}: 1abcdefghijklmnopqrstuvwxyzABCDEFGHIJKL
241 if constraint in NUMERIC_CONSTRAINTS: 1abcdefghijklmnopqrstuvwxyzABCDEFGHIJKL
242 json_schema_constraint = constraint 1abcdefghijklmnopqrstuvwxyzABCDEFGHIJKL
243 elif constraint in LENGTH_CONSTRAINTS: 243 ↛ 255line 243 didn't jump to line 255 because the condition on line 243 was always true1abcdefghijklmnopqrstuvwxyzABCDEFGHIJKL
244 inner_schema = schema 1abcdefghijklmnopqrstuvwxyzABCDEFGHIJKL
245 while inner_schema['type'] in {'function-before', 'function-wrap', 'function-after'}: 1abcdefghijklmnopqrstuvwxyzABCDEFGHIJKL
246 inner_schema = inner_schema['schema'] # type: ignore 1abcdefghijklmnopqrstuvwxyzABCDEFGHIJKL
247 inner_schema_type = inner_schema['type'] 1abcdefghijklmnopqrstuvwxyzABCDEFGHIJKL
248 if inner_schema_type == 'list' or ( 1abcdefghijklmnopqrstuvwxyzABCDEFGHIJKL
249 inner_schema_type == 'json-or-python' and inner_schema['json_schema']['type'] == 'list' # type: ignore
250 ):
251 json_schema_constraint = 'minItems' if constraint == 'min_length' else 'maxItems' 1abcdefghijklmnopqrstuvwxyzABCDEFGHIJKL
252 else:
253 json_schema_constraint = 'minLength' if constraint == 'min_length' else 'maxLength' 1abcdefghijklmnopqrstuvwxyzABCDEFGHIJKL
255 schema = cs.no_info_after_validator_function( 1abcdefghijklmnopqrstuvwxyzABCDEFGHIJKL
256 partial(get_constraint_validator(constraint), **{constraint: value}), schema
257 )
258 add_js_update_schema(schema, lambda: {json_schema_constraint: as_jsonable_value(value)}) 1abcdefghijklmnopqrstuvwxyzABCDEFGHIJKL
259 elif constraint == 'allow_inf_nan' and value is False: 259 ↛ 265line 259 didn't jump to line 265 because the condition on line 259 was always true1abcdefghijklmnopqrstuvwxyzABCDEFGHIJKL
260 schema = cs.no_info_after_validator_function( 1abcdefghijklmnopqrstuvwxyzABCDEFGHIJKL
261 forbid_inf_nan_check,
262 schema,
263 )
264 else:
265 raise RuntimeError(f'Unable to apply constraint {constraint} to schema {schema_type}')
267 for annotation in other_metadata: 1abcdefghijklmnopqrstuvwxyzMNOPQRSTUVABCDEFGHIJKL
268 if (annotation_type := type(annotation)) in (at_to_constraint_map := _get_at_to_constraint_map()): 268 ↛ 269line 268 didn't jump to line 269 because the condition on line 268 was never true1abcdefghijklmnopqrstuvwxyzMNOPQRSTUVABCDEFGHIJKL
269 constraint = at_to_constraint_map[annotation_type]
270 schema = cs.no_info_after_validator_function(
271 partial(get_constraint_validator(constraint), {constraint: getattr(annotation, constraint)}), schema
272 )
273 continue
274 elif isinstance(annotation, at.Predicate): 1abcdefghijklmnopqrstuvwxyzMNOPQRSTUVABCDEFGHIJKL
275 predicate_name = f'{annotation.func.__qualname__} ' if hasattr(annotation.func, '__qualname__') else '' 1abcdefghijklmnopqrstuvwxyzABCDEFGHIJKL
277 def val_func(v: Any) -> Any: 1abcdefghijklmnopqrstuvwxyzABCDEFGHIJKL
278 # annotation.func may also raise an exception, let it pass through
279 if not annotation.func(v): 1abcdefghijklmnopqrstuvwxyzABCDEFGHIJKL
280 raise PydanticCustomError( 1abcdefghijklmnopqrstuvwxyzABCDEFGHIJKL
281 'predicate_failed',
282 f'Predicate {predicate_name}failed', # type: ignore
283 )
284 return v 1abcdefghijklmnopqrstuvwxyzABCDEFGHIJKL
286 schema = cs.no_info_after_validator_function(val_func, schema) 1abcdefghijklmnopqrstuvwxyzABCDEFGHIJKL
287 else:
288 # ignore any other unknown metadata
289 return None 1abcdefghijklmnopqrstuvwxyzMNOPQRSTUVABCDEFGHIJKL
291 if chain_schema_steps: 1abcdefghijklmnopqrstuvwxyzABCDEFGHIJKL
292 chain_schema_steps = [schema] + chain_schema_steps 1abcdefghijklmnopqrstuvwxyzABCDEFGHIJKL
293 return cs.chain_schema(chain_schema_steps) 1abcdefghijklmnopqrstuvwxyzABCDEFGHIJKL
295 return schema 1abcdefghijklmnopqrstuvwxyzABCDEFGHIJKL
298def collect_known_metadata(annotations: Iterable[Any]) -> tuple[dict[str, Any], list[Any]]: 1abcdefghijklmnopqrstuvwxyzMNOPQRSTUVABCDEFGHIJKL
299 """Split `annotations` into known metadata and unknown annotations.
301 Args:
302 annotations: An iterable of annotations.
304 Returns:
305 A tuple contains a dict of known metadata and a list of unknown annotations.
307 Example:
308 ```py
309 from annotated_types import Gt, Len
311 from pydantic._internal._known_annotated_metadata import collect_known_metadata
313 print(collect_known_metadata([Gt(1), Len(42), ...]))
314 #> ({'gt': 1, 'min_length': 42}, [Ellipsis])
315 ```
316 """
317 annotations = expand_grouped_metadata(annotations) 1abcdefghijklmnopqrstuvwxyzMNOPQRSTUVABCDEFGHIJKL
319 res: dict[str, Any] = {} 1abcdefghijklmnopqrstuvwxyzMNOPQRSTUVABCDEFGHIJKL
320 remaining: list[Any] = [] 1abcdefghijklmnopqrstuvwxyzMNOPQRSTUVABCDEFGHIJKL
322 for annotation in annotations: 1abcdefghijklmnopqrstuvwxyzMNOPQRSTUVABCDEFGHIJKL
323 # isinstance(annotation, PydanticMetadata) also covers ._fields:_PydanticGeneralMetadata
324 if isinstance(annotation, PydanticMetadata): 1abcdefghijklmnopqrstuvwxyzMNOPQRSTUVABCDEFGHIJKL
325 res.update(annotation.__dict__) 1abcdefghijklmnopqrstuvwxyzABCDEFGHIJKL
326 # we don't use dataclasses.asdict because that recursively calls asdict on the field values
327 elif (annotation_type := type(annotation)) in (at_to_constraint_map := _get_at_to_constraint_map()): 1abcdefghijklmnopqrstuvwxyzMNOPQRSTUVABCDEFGHIJKL
328 constraint = at_to_constraint_map[annotation_type] 1abcdefghijklmnopqrstuvwxyzABCDEFGHIJKL
329 res[constraint] = getattr(annotation, constraint) 1abcdefghijklmnopqrstuvwxyzABCDEFGHIJKL
330 elif isinstance(annotation, type) and issubclass(annotation, PydanticMetadata): 1abcdefghijklmnopqrstuvwxyzMNOPQRSTUVABCDEFGHIJKL
331 # also support PydanticMetadata classes being used without initialisation,
332 # e.g. `Annotated[int, Strict]` as well as `Annotated[int, Strict()]`
333 res.update({k: v for k, v in vars(annotation).items() if not k.startswith('_')}) 1abcdefghijklmnopqrstuvwxyzABCDEFGHIJKL
334 else:
335 remaining.append(annotation) 1abcdefghijklmnopqrstuvwxyzMNOPQRSTUVABCDEFGHIJKL
336 # Nones can sneak in but pydantic-core will reject them
337 # it'd be nice to clean things up so we don't put in None (we probably don't _need_ to, it was just easier)
338 # but this is simple enough to kick that can down the road
339 res = {k: v for k, v in res.items() if v is not None} 1abcdefghijklmnopqrstuvwxyzMNOPQRSTUVABCDEFGHIJKL
340 return res, remaining 1abcdefghijklmnopqrstuvwxyzMNOPQRSTUVABCDEFGHIJKL
343def check_metadata(metadata: dict[str, Any], allowed: Iterable[str], source_type: Any) -> None: 1abcdefghijklmnopqrstuvwxyzMNOPQRSTUVABCDEFGHIJKL
344 """A small utility function to validate that the given metadata can be applied to the target.
345 More than saving lines of code, this gives us a consistent error message for all of our internal implementations.
347 Args:
348 metadata: A dict of metadata.
349 allowed: An iterable of allowed metadata.
350 source_type: The source type.
352 Raises:
353 TypeError: If there is metadatas that can't be applied on source type.
354 """
355 unknown = metadata.keys() - set(allowed) 1abcdefghijklmnopqrstuvwxyzMNOPQRSTUVABCDEFGHIJKL
356 if unknown: 1abcdefghijklmnopqrstuvwxyzMNOPQRSTUVABCDEFGHIJKL
357 raise TypeError( 1abcdefghijklmnopqrstuvwxyzABCDEFGHIJKL
358 f'The following constraints cannot be applied to {source_type!r}: {", ".join([f"{k!r}" for k in unknown])}'
359 )