1from __future__ import annotations
2
3from collections import defaultdict
4from collections.abc import Iterable
5from copy import copy
6from functools import lru_cache, partial
7from typing import TYPE_CHECKING, Any
8
9from pydantic_core import CoreSchema, PydanticCustomError, ValidationError, to_jsonable_python
10from pydantic_core import core_schema as cs
11
12from ._fields import PydanticMetadata
13from ._import_utils import import_cached_field_info
14
15if TYPE_CHECKING:
16 pass
17
18STRICT = {'strict'}
19FAIL_FAST = {'fail_fast'}
20LENGTH_CONSTRAINTS = {'min_length', 'max_length'}
21INEQUALITY = {'le', 'ge', 'lt', 'gt'}
22NUMERIC_CONSTRAINTS = {'multiple_of', *INEQUALITY}
23ALLOW_INF_NAN = {'allow_inf_nan'}
24
25STR_CONSTRAINTS = {
26 *LENGTH_CONSTRAINTS,
27 *STRICT,
28 'strip_whitespace',
29 'to_lower',
30 'to_upper',
31 'pattern',
32 'coerce_numbers_to_str',
33 'ascii_only',
34}
35BYTES_CONSTRAINTS = {*LENGTH_CONSTRAINTS, *STRICT}
36
37LIST_CONSTRAINTS = {*LENGTH_CONSTRAINTS, *STRICT, *FAIL_FAST}
38TUPLE_CONSTRAINTS = {*LENGTH_CONSTRAINTS, *STRICT, *FAIL_FAST}
39SET_CONSTRAINTS = {*LENGTH_CONSTRAINTS, *STRICT, *FAIL_FAST}
40DICT_CONSTRAINTS = {*LENGTH_CONSTRAINTS, *STRICT}
41GENERATOR_CONSTRAINTS = {*LENGTH_CONSTRAINTS, *STRICT}
42SEQUENCE_CONSTRAINTS = {*LENGTH_CONSTRAINTS, *FAIL_FAST}
43
44FLOAT_CONSTRAINTS = {*NUMERIC_CONSTRAINTS, *ALLOW_INF_NAN, *STRICT}
45DECIMAL_CONSTRAINTS = {'max_digits', 'decimal_places', *FLOAT_CONSTRAINTS}
46INT_CONSTRAINTS = {*NUMERIC_CONSTRAINTS, *ALLOW_INF_NAN, *STRICT}
47BOOL_CONSTRAINTS = STRICT
48UUID_CONSTRAINTS = STRICT
49
50DATE_TIME_CONSTRAINTS = {*NUMERIC_CONSTRAINTS, *STRICT}
51TIMEDELTA_CONSTRAINTS = {*NUMERIC_CONSTRAINTS, *STRICT}
52TIME_CONSTRAINTS = {*NUMERIC_CONSTRAINTS, *STRICT}
53LAX_OR_STRICT_CONSTRAINTS = STRICT
54ENUM_CONSTRAINTS = STRICT
55COMPLEX_CONSTRAINTS = STRICT
56
57UNION_CONSTRAINTS = {'union_mode'}
58URL_CONSTRAINTS = {
59 'max_length',
60 'allowed_schemes',
61 'host_required',
62 'default_host',
63 'default_port',
64 'default_path',
65}
66
67TEXT_SCHEMA_TYPES = ('str', 'bytes', 'url', 'multi-host-url')
68SEQUENCE_SCHEMA_TYPES = ('list', 'tuple', 'set', 'frozenset', 'generator', *TEXT_SCHEMA_TYPES)
69NUMERIC_SCHEMA_TYPES = ('float', 'int', 'date', 'time', 'timedelta', 'datetime')
70
71CONSTRAINTS_TO_ALLOWED_SCHEMAS: dict[str, set[str]] = defaultdict(set)
72
73constraint_schema_pairings: list[tuple[set[str], tuple[str, ...]]] = [
74 (STR_CONSTRAINTS, TEXT_SCHEMA_TYPES),
75 (BYTES_CONSTRAINTS, ('bytes',)),
76 (LIST_CONSTRAINTS, ('list',)),
77 (TUPLE_CONSTRAINTS, ('tuple',)),
78 (SET_CONSTRAINTS, ('set', 'frozenset')),
79 (DICT_CONSTRAINTS, ('dict',)),
80 (GENERATOR_CONSTRAINTS, ('generator',)),
81 (FLOAT_CONSTRAINTS, ('float',)),
82 (INT_CONSTRAINTS, ('int',)),
83 (DATE_TIME_CONSTRAINTS, ('date', 'time', 'datetime', 'timedelta')),
84 # TODO: this is a bit redundant, we could probably avoid some of these
85 (STRICT, (*TEXT_SCHEMA_TYPES, *SEQUENCE_SCHEMA_TYPES, *NUMERIC_SCHEMA_TYPES, 'typed-dict', 'model')),
86 (UNION_CONSTRAINTS, ('union',)),
87 (URL_CONSTRAINTS, ('url', 'multi-host-url')),
88 (BOOL_CONSTRAINTS, ('bool',)),
89 (UUID_CONSTRAINTS, ('uuid',)),
90 (LAX_OR_STRICT_CONSTRAINTS, ('lax-or-strict',)),
91 (ENUM_CONSTRAINTS, ('enum',)),
92 (DECIMAL_CONSTRAINTS, ('decimal',)),
93 (COMPLEX_CONSTRAINTS, ('complex',)),
94]
95
96for constraints, schemas in constraint_schema_pairings:
97 for c in constraints:
98 CONSTRAINTS_TO_ALLOWED_SCHEMAS[c].update(schemas)
99
100
101def as_jsonable_value(v: Any) -> Any:
102 if type(v) not in (int, str, float, bytes, bool, type(None)):
103 return to_jsonable_python(v)
104 return v
105
106
107def expand_grouped_metadata(annotations: Iterable[Any]) -> Iterable[Any]:
108 """Expand the annotations.
109
110 Args:
111 annotations: An iterable of annotations.
112
113 Returns:
114 An iterable of expanded annotations.
115
116 Example:
117 ```python
118 from annotated_types import Ge, Len
119
120 from pydantic._internal._known_annotated_metadata import expand_grouped_metadata
121
122 print(list(expand_grouped_metadata([Ge(4), Len(5)])))
123 #> [Ge(ge=4), MinLen(min_length=5)]
124 ```
125 """
126 import annotated_types as at
127
128 FieldInfo = import_cached_field_info()
129
130 for annotation in annotations:
131 if isinstance(annotation, at.GroupedMetadata):
132 yield from annotation
133 elif isinstance(annotation, FieldInfo):
134 yield from annotation.metadata
135 # this is a bit problematic in that it results in duplicate metadata
136 # all of our "consumers" can handle it, but it is not ideal
137 # we probably should split up FieldInfo into:
138 # - annotated types metadata
139 # - individual metadata known only to Pydantic
140 annotation = copy(annotation)
141 annotation.metadata = []
142 yield annotation
143 else:
144 yield annotation
145
146
147@lru_cache
148def _get_at_to_constraint_map() -> dict[type, str]:
149 """Return a mapping of annotated types to constraints.
150
151 Normally, we would define a mapping like this in the module scope, but we can't do that
152 because we don't permit module level imports of `annotated_types`, in an attempt to speed up
153 the import time of `pydantic`. We still only want to have this dictionary defined in one place,
154 so we use this function to cache the result.
155 """
156 import annotated_types as at
157
158 return {
159 at.Gt: 'gt',
160 at.Ge: 'ge',
161 at.Lt: 'lt',
162 at.Le: 'le',
163 at.MultipleOf: 'multiple_of',
164 at.MinLen: 'min_length',
165 at.MaxLen: 'max_length',
166 }
167
168
169def apply_known_metadata(annotation: Any, schema: CoreSchema) -> CoreSchema | None: # noqa: C901
170 """Apply `annotation` to `schema` if it is an annotation we know about (Gt, Le, etc.).
171 Otherwise return `None`.
172
173 This does not handle all known annotations. If / when it does, it can always
174 return a CoreSchema and return the unmodified schema if the annotation should be ignored.
175
176 Assumes that GroupedMetadata has already been expanded via `expand_grouped_metadata`.
177
178 Args:
179 annotation: The annotation.
180 schema: The schema.
181
182 Returns:
183 An updated schema with annotation if it is an annotation we know about, `None` otherwise.
184
185 Raises:
186 RuntimeError: If a constraint can't be applied to a specific schema type.
187 ValueError: If an unknown constraint is encountered.
188 """
189 import annotated_types as at
190
191 from ._validators import NUMERIC_VALIDATOR_LOOKUP, forbid_inf_nan_check
192
193 schema = schema.copy()
194 schema_update, other_metadata = collect_known_metadata([annotation])
195 schema_type = schema['type']
196
197 chain_schema_constraints: set[str] = {
198 'pattern',
199 'strip_whitespace',
200 'to_lower',
201 'to_upper',
202 'coerce_numbers_to_str',
203 'ascii_only',
204 }
205 chain_schema_steps: list[CoreSchema] = []
206
207 for constraint, value in schema_update.items():
208 if constraint not in CONSTRAINTS_TO_ALLOWED_SCHEMAS:
209 raise ValueError(f'Unknown constraint {constraint}')
210 allowed_schemas = CONSTRAINTS_TO_ALLOWED_SCHEMAS[constraint]
211
212 # if it becomes necessary to handle more than one constraint
213 # in this recursive case with function-after or function-wrap, we should refactor
214 # this is a bit challenging because we sometimes want to apply constraints to the inner schema,
215 # whereas other times we want to wrap the existing schema with a new one that enforces a new constraint.
216 if schema_type in {'function-before', 'function-wrap', 'function-after'} and constraint == 'strict':
217 schema['schema'] = apply_known_metadata(annotation, schema['schema']) # type: ignore # schema is function schema
218 return schema
219
220 # if we're allowed to apply constraint directly to the schema, like le to int, do that
221 if schema_type in allowed_schemas:
222 if constraint == 'union_mode' and schema_type == 'union':
223 schema['mode'] = value # type: ignore # schema is UnionSchema
224 else:
225 schema[constraint] = value
226 continue
227
228 # else, apply a function after validator to the schema to enforce the corresponding constraint
229 if constraint in chain_schema_constraints:
230
231 def _apply_constraint_with_incompatibility_info(
232 value: Any, handler: cs.ValidatorFunctionWrapHandler
233 ) -> Any:
234 try:
235 x = handler(value)
236 except ValidationError as ve:
237 # if the error is about the type, it's likely that the constraint is incompatible the type of the field
238 # for example, the following invalid schema wouldn't be caught during schema build, but rather at this point
239 # with a cryptic 'string_type' error coming from the string validator,
240 # that we'd rather express as a constraint incompatibility error (TypeError)
241 # Annotated[list[int], Field(pattern='abc')]
242 if 'type' in ve.errors()[0]['type']:
243 raise TypeError(
244 f"Unable to apply constraint '{constraint}' to supplied value {value} for schema of type '{schema_type}'" # noqa: B023
245 )
246 raise ve
247 return x
248
249 chain_schema_steps.append(
250 cs.no_info_wrap_validator_function(
251 _apply_constraint_with_incompatibility_info, cs.str_schema(**{constraint: value})
252 )
253 )
254 elif constraint in NUMERIC_VALIDATOR_LOOKUP:
255 if constraint in LENGTH_CONSTRAINTS:
256 inner_schema = schema
257 while inner_schema['type'] in {'function-before', 'function-wrap', 'function-after'}:
258 inner_schema = inner_schema['schema'] # type: ignore
259 inner_schema_type = inner_schema['type']
260 if inner_schema_type == 'list' or (
261 inner_schema_type == 'json-or-python' and inner_schema['json_schema']['type'] == 'list' # type: ignore
262 ):
263 js_constraint_key = 'minItems' if constraint == 'min_length' else 'maxItems'
264 else:
265 js_constraint_key = 'minLength' if constraint == 'min_length' else 'maxLength'
266 else:
267 js_constraint_key = constraint
268
269 schema = cs.no_info_after_validator_function(
270 partial(NUMERIC_VALIDATOR_LOOKUP[constraint], **{constraint: value}), schema
271 )
272 metadata = schema.get('metadata', {})
273 if (existing_json_schema_updates := metadata.get('pydantic_js_updates')) is not None:
274 metadata['pydantic_js_updates'] = {
275 **existing_json_schema_updates,
276 **{js_constraint_key: as_jsonable_value(value)},
277 }
278 else:
279 metadata['pydantic_js_updates'] = {js_constraint_key: as_jsonable_value(value)}
280 schema['metadata'] = metadata
281 elif constraint == 'allow_inf_nan' and value is False:
282 schema = cs.no_info_after_validator_function(
283 forbid_inf_nan_check,
284 schema,
285 )
286 else:
287 # It's rare that we'd get here, but it's possible if we add a new constraint and forget to handle it
288 # Most constraint errors are caught at runtime during attempted application
289 raise RuntimeError(f"Unable to apply constraint '{constraint}' to schema of type '{schema_type}'")
290
291 for annotation in other_metadata:
292 if (annotation_type := type(annotation)) in (at_to_constraint_map := _get_at_to_constraint_map()):
293 constraint = at_to_constraint_map[annotation_type]
294 validator = NUMERIC_VALIDATOR_LOOKUP.get(constraint)
295 if validator is None:
296 raise ValueError(f'Unknown constraint {constraint}')
297 schema = cs.no_info_after_validator_function(
298 partial(validator, {constraint: getattr(annotation, constraint)}), schema
299 )
300 continue
301 elif isinstance(annotation, (at.Predicate, at.Not)):
302 predicate_name = f'{annotation.func.__qualname__!r} ' if hasattr(annotation.func, '__qualname__') else ''
303
304 # Note: B023 is ignored because even though we iterate over `other_metadata`, it is guaranteed
305 # to be of length 1. `apply_known_metadata()` is called from `GenerateSchema`, where annotations
306 # were already expanded via `expand_grouped_metadata()`. Confusing, but this falls into the annotations
307 # refactor.
308 if isinstance(annotation, at.Predicate):
309
310 def val_func(v: Any) -> Any:
311 predicate_satisfied = annotation.func(v) # noqa: B023
312 if not predicate_satisfied:
313 raise PydanticCustomError(
314 'predicate_failed',
315 f'Predicate {predicate_name}failed', # pyright: ignore[reportArgumentType] # noqa: B023
316 )
317 return v
318
319 else:
320
321 def val_func(v: Any) -> Any:
322 predicate_satisfied = annotation.func(v) # noqa: B023
323 if predicate_satisfied:
324 raise PydanticCustomError(
325 'not_operation_failed',
326 f'Not of {predicate_name}failed', # pyright: ignore[reportArgumentType] # noqa: B023
327 )
328 return v
329
330 schema = cs.no_info_after_validator_function(val_func, schema)
331 else:
332 # ignore any other unknown metadata
333 return None
334
335 if chain_schema_steps:
336 chain_schema_steps = [schema] + chain_schema_steps
337 return cs.chain_schema(chain_schema_steps)
338
339 return schema
340
341
342def collect_known_metadata(annotations: Iterable[Any]) -> tuple[dict[str, Any], list[Any]]:
343 """Split `annotations` into known metadata and unknown annotations.
344
345 Args:
346 annotations: An iterable of annotations.
347
348 Returns:
349 A tuple contains a dict of known metadata and a list of unknown annotations.
350
351 Example:
352 ```python
353 from annotated_types import Gt, Len
354
355 from pydantic._internal._known_annotated_metadata import collect_known_metadata
356
357 print(collect_known_metadata([Gt(1), Len(42), ...]))
358 #> ({'gt': 1, 'min_length': 42}, [Ellipsis])
359 ```
360 """
361 annotations = expand_grouped_metadata(annotations)
362
363 res: dict[str, Any] = {}
364 remaining: list[Any] = []
365
366 for annotation in annotations:
367 # isinstance(annotation, PydanticMetadata) also covers ._fields:_PydanticGeneralMetadata
368 if isinstance(annotation, PydanticMetadata):
369 res.update(annotation.__dict__)
370 # we don't use dataclasses.asdict because that recursively calls asdict on the field values
371 elif (annotation_type := type(annotation)) in (at_to_constraint_map := _get_at_to_constraint_map()):
372 constraint = at_to_constraint_map[annotation_type]
373 res[constraint] = getattr(annotation, constraint)
374 elif isinstance(annotation, type) and issubclass(annotation, PydanticMetadata):
375 # also support PydanticMetadata classes being used without initialisation,
376 # e.g. `Annotated[int, Strict]` as well as `Annotated[int, Strict()]`
377 res.update({k: v for k, v in vars(annotation).items() if not k.startswith('_')})
378 else:
379 remaining.append(annotation)
380 # Nones can sneak in but pydantic-core will reject them
381 # 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)
382 # but this is simple enough to kick that can down the road
383 res = {k: v for k, v in res.items() if v is not None}
384 return res, remaining
385
386
387def check_metadata(metadata: dict[str, Any], allowed: Iterable[str], source_type: Any) -> None:
388 """A small utility function to validate that the given metadata can be applied to the target.
389 More than saving lines of code, this gives us a consistent error message for all of our internal implementations.
390
391 Args:
392 metadata: A dict of metadata.
393 allowed: An iterable of allowed metadata.
394 source_type: The source type.
395
396 Raises:
397 TypeError: If there is metadatas that can't be applied on source type.
398 """
399 unknown = metadata.keys() - set(allowed)
400 if unknown:
401 raise TypeError(
402 f'The following constraints cannot be applied to {source_type!r}: {", ".join([f"{k!r}" for k in unknown])}'
403 )