pipeline.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654
  1. """Experimental pipeline API functionality. Be careful with this API, it's subject to change."""
  2. from __future__ import annotations
  3. import datetime
  4. import operator
  5. import re
  6. import sys
  7. from collections import deque
  8. from collections.abc import Container
  9. from dataclasses import dataclass
  10. from decimal import Decimal
  11. from functools import cached_property, partial
  12. from re import Pattern
  13. from typing import TYPE_CHECKING, Annotated, Any, Callable, Generic, Protocol, TypeVar, Union, overload
  14. import annotated_types
  15. if TYPE_CHECKING:
  16. from pydantic import GetCoreSchemaHandler
  17. from pydantic_core import PydanticCustomError
  18. from pydantic_core import core_schema as cs
  19. from pydantic import Strict
  20. from pydantic._internal._internal_dataclass import slots_true as _slots_true
  21. if sys.version_info < (3, 10):
  22. EllipsisType = type(Ellipsis)
  23. else:
  24. from types import EllipsisType
  25. __all__ = ['validate_as', 'validate_as_deferred', 'transform']
  26. _slots_frozen = {**_slots_true, 'frozen': True}
  27. @dataclass(**_slots_frozen)
  28. class _ValidateAs:
  29. tp: type[Any]
  30. strict: bool = False
  31. @dataclass
  32. class _ValidateAsDefer:
  33. func: Callable[[], type[Any]]
  34. @cached_property
  35. def tp(self) -> type[Any]:
  36. return self.func()
  37. @dataclass(**_slots_frozen)
  38. class _Transform:
  39. func: Callable[[Any], Any]
  40. @dataclass(**_slots_frozen)
  41. class _PipelineOr:
  42. left: _Pipeline[Any, Any]
  43. right: _Pipeline[Any, Any]
  44. @dataclass(**_slots_frozen)
  45. class _PipelineAnd:
  46. left: _Pipeline[Any, Any]
  47. right: _Pipeline[Any, Any]
  48. @dataclass(**_slots_frozen)
  49. class _Eq:
  50. value: Any
  51. @dataclass(**_slots_frozen)
  52. class _NotEq:
  53. value: Any
  54. @dataclass(**_slots_frozen)
  55. class _In:
  56. values: Container[Any]
  57. @dataclass(**_slots_frozen)
  58. class _NotIn:
  59. values: Container[Any]
  60. _ConstraintAnnotation = Union[
  61. annotated_types.Le,
  62. annotated_types.Ge,
  63. annotated_types.Lt,
  64. annotated_types.Gt,
  65. annotated_types.Len,
  66. annotated_types.MultipleOf,
  67. annotated_types.Timezone,
  68. annotated_types.Interval,
  69. annotated_types.Predicate,
  70. # common predicates not included in annotated_types
  71. _Eq,
  72. _NotEq,
  73. _In,
  74. _NotIn,
  75. # regular expressions
  76. Pattern[str],
  77. ]
  78. @dataclass(**_slots_frozen)
  79. class _Constraint:
  80. constraint: _ConstraintAnnotation
  81. _Step = Union[_ValidateAs, _ValidateAsDefer, _Transform, _PipelineOr, _PipelineAnd, _Constraint]
  82. _InT = TypeVar('_InT')
  83. _OutT = TypeVar('_OutT')
  84. _NewOutT = TypeVar('_NewOutT')
  85. class _FieldTypeMarker:
  86. pass
  87. # TODO: ultimately, make this public, see https://github.com/pydantic/pydantic/pull/9459#discussion_r1628197626
  88. # Also, make this frozen eventually, but that doesn't work right now because of the generic base
  89. # Which attempts to modify __orig_base__ and such.
  90. # We could go with a manual freeze, but that seems overkill for now.
  91. @dataclass(**_slots_true)
  92. class _Pipeline(Generic[_InT, _OutT]):
  93. """Abstract representation of a chain of validation, transformation, and parsing steps."""
  94. _steps: tuple[_Step, ...]
  95. def transform(
  96. self,
  97. func: Callable[[_OutT], _NewOutT],
  98. ) -> _Pipeline[_InT, _NewOutT]:
  99. """Transform the output of the previous step.
  100. If used as the first step in a pipeline, the type of the field is used.
  101. That is, the transformation is applied to after the value is parsed to the field's type.
  102. """
  103. return _Pipeline[_InT, _NewOutT](self._steps + (_Transform(func),))
  104. @overload
  105. def validate_as(self, tp: type[_NewOutT], *, strict: bool = ...) -> _Pipeline[_InT, _NewOutT]: ...
  106. @overload
  107. def validate_as(self, tp: EllipsisType, *, strict: bool = ...) -> _Pipeline[_InT, Any]: # type: ignore
  108. ...
  109. def validate_as(self, tp: type[_NewOutT] | EllipsisType, *, strict: bool = False) -> _Pipeline[_InT, Any]: # type: ignore
  110. """Validate / parse the input into a new type.
  111. If no type is provided, the type of the field is used.
  112. Types are parsed in Pydantic's `lax` mode by default,
  113. but you can enable `strict` mode by passing `strict=True`.
  114. """
  115. if isinstance(tp, EllipsisType):
  116. return _Pipeline[_InT, Any](self._steps + (_ValidateAs(_FieldTypeMarker, strict=strict),))
  117. return _Pipeline[_InT, _NewOutT](self._steps + (_ValidateAs(tp, strict=strict),))
  118. def validate_as_deferred(self, func: Callable[[], type[_NewOutT]]) -> _Pipeline[_InT, _NewOutT]:
  119. """Parse the input into a new type, deferring resolution of the type until the current class
  120. is fully defined.
  121. This is useful when you need to reference the class in it's own type annotations.
  122. """
  123. return _Pipeline[_InT, _NewOutT](self._steps + (_ValidateAsDefer(func),))
  124. # constraints
  125. @overload
  126. def constrain(self: _Pipeline[_InT, _NewOutGe], constraint: annotated_types.Ge) -> _Pipeline[_InT, _NewOutGe]: ...
  127. @overload
  128. def constrain(self: _Pipeline[_InT, _NewOutGt], constraint: annotated_types.Gt) -> _Pipeline[_InT, _NewOutGt]: ...
  129. @overload
  130. def constrain(self: _Pipeline[_InT, _NewOutLe], constraint: annotated_types.Le) -> _Pipeline[_InT, _NewOutLe]: ...
  131. @overload
  132. def constrain(self: _Pipeline[_InT, _NewOutLt], constraint: annotated_types.Lt) -> _Pipeline[_InT, _NewOutLt]: ...
  133. @overload
  134. def constrain(
  135. self: _Pipeline[_InT, _NewOutLen], constraint: annotated_types.Len
  136. ) -> _Pipeline[_InT, _NewOutLen]: ...
  137. @overload
  138. def constrain(
  139. self: _Pipeline[_InT, _NewOutT], constraint: annotated_types.MultipleOf
  140. ) -> _Pipeline[_InT, _NewOutT]: ...
  141. @overload
  142. def constrain(
  143. self: _Pipeline[_InT, _NewOutDatetime], constraint: annotated_types.Timezone
  144. ) -> _Pipeline[_InT, _NewOutDatetime]: ...
  145. @overload
  146. def constrain(self: _Pipeline[_InT, _OutT], constraint: annotated_types.Predicate) -> _Pipeline[_InT, _OutT]: ...
  147. @overload
  148. def constrain(
  149. self: _Pipeline[_InT, _NewOutInterval], constraint: annotated_types.Interval
  150. ) -> _Pipeline[_InT, _NewOutInterval]: ...
  151. @overload
  152. def constrain(self: _Pipeline[_InT, _OutT], constraint: _Eq) -> _Pipeline[_InT, _OutT]: ...
  153. @overload
  154. def constrain(self: _Pipeline[_InT, _OutT], constraint: _NotEq) -> _Pipeline[_InT, _OutT]: ...
  155. @overload
  156. def constrain(self: _Pipeline[_InT, _OutT], constraint: _In) -> _Pipeline[_InT, _OutT]: ...
  157. @overload
  158. def constrain(self: _Pipeline[_InT, _OutT], constraint: _NotIn) -> _Pipeline[_InT, _OutT]: ...
  159. @overload
  160. def constrain(self: _Pipeline[_InT, _NewOutT], constraint: Pattern[str]) -> _Pipeline[_InT, _NewOutT]: ...
  161. def constrain(self, constraint: _ConstraintAnnotation) -> Any:
  162. """Constrain a value to meet a certain condition.
  163. We support most conditions from `annotated_types`, as well as regular expressions.
  164. Most of the time you'll be calling a shortcut method like `gt`, `lt`, `len`, etc
  165. so you don't need to call this directly.
  166. """
  167. return _Pipeline[_InT, _OutT](self._steps + (_Constraint(constraint),))
  168. def predicate(self: _Pipeline[_InT, _NewOutT], func: Callable[[_NewOutT], bool]) -> _Pipeline[_InT, _NewOutT]:
  169. """Constrain a value to meet a certain predicate."""
  170. return self.constrain(annotated_types.Predicate(func))
  171. def gt(self: _Pipeline[_InT, _NewOutGt], gt: _NewOutGt) -> _Pipeline[_InT, _NewOutGt]:
  172. """Constrain a value to be greater than a certain value."""
  173. return self.constrain(annotated_types.Gt(gt))
  174. def lt(self: _Pipeline[_InT, _NewOutLt], lt: _NewOutLt) -> _Pipeline[_InT, _NewOutLt]:
  175. """Constrain a value to be less than a certain value."""
  176. return self.constrain(annotated_types.Lt(lt))
  177. def ge(self: _Pipeline[_InT, _NewOutGe], ge: _NewOutGe) -> _Pipeline[_InT, _NewOutGe]:
  178. """Constrain a value to be greater than or equal to a certain value."""
  179. return self.constrain(annotated_types.Ge(ge))
  180. def le(self: _Pipeline[_InT, _NewOutLe], le: _NewOutLe) -> _Pipeline[_InT, _NewOutLe]:
  181. """Constrain a value to be less than or equal to a certain value."""
  182. return self.constrain(annotated_types.Le(le))
  183. def len(self: _Pipeline[_InT, _NewOutLen], min_len: int, max_len: int | None = None) -> _Pipeline[_InT, _NewOutLen]:
  184. """Constrain a value to have a certain length."""
  185. return self.constrain(annotated_types.Len(min_len, max_len))
  186. @overload
  187. def multiple_of(self: _Pipeline[_InT, _NewOutDiv], multiple_of: _NewOutDiv) -> _Pipeline[_InT, _NewOutDiv]: ...
  188. @overload
  189. def multiple_of(self: _Pipeline[_InT, _NewOutMod], multiple_of: _NewOutMod) -> _Pipeline[_InT, _NewOutMod]: ...
  190. def multiple_of(self: _Pipeline[_InT, Any], multiple_of: Any) -> _Pipeline[_InT, Any]:
  191. """Constrain a value to be a multiple of a certain number."""
  192. return self.constrain(annotated_types.MultipleOf(multiple_of))
  193. def eq(self: _Pipeline[_InT, _OutT], value: _OutT) -> _Pipeline[_InT, _OutT]:
  194. """Constrain a value to be equal to a certain value."""
  195. return self.constrain(_Eq(value))
  196. def not_eq(self: _Pipeline[_InT, _OutT], value: _OutT) -> _Pipeline[_InT, _OutT]:
  197. """Constrain a value to not be equal to a certain value."""
  198. return self.constrain(_NotEq(value))
  199. def in_(self: _Pipeline[_InT, _OutT], values: Container[_OutT]) -> _Pipeline[_InT, _OutT]:
  200. """Constrain a value to be in a certain set."""
  201. return self.constrain(_In(values))
  202. def not_in(self: _Pipeline[_InT, _OutT], values: Container[_OutT]) -> _Pipeline[_InT, _OutT]:
  203. """Constrain a value to not be in a certain set."""
  204. return self.constrain(_NotIn(values))
  205. # timezone methods
  206. def datetime_tz_naive(self: _Pipeline[_InT, datetime.datetime]) -> _Pipeline[_InT, datetime.datetime]:
  207. return self.constrain(annotated_types.Timezone(None))
  208. def datetime_tz_aware(self: _Pipeline[_InT, datetime.datetime]) -> _Pipeline[_InT, datetime.datetime]:
  209. return self.constrain(annotated_types.Timezone(...))
  210. def datetime_tz(
  211. self: _Pipeline[_InT, datetime.datetime], tz: datetime.tzinfo
  212. ) -> _Pipeline[_InT, datetime.datetime]:
  213. return self.constrain(annotated_types.Timezone(tz)) # type: ignore
  214. def datetime_with_tz(
  215. self: _Pipeline[_InT, datetime.datetime], tz: datetime.tzinfo | None
  216. ) -> _Pipeline[_InT, datetime.datetime]:
  217. return self.transform(partial(datetime.datetime.replace, tzinfo=tz))
  218. # string methods
  219. def str_lower(self: _Pipeline[_InT, str]) -> _Pipeline[_InT, str]:
  220. return self.transform(str.lower)
  221. def str_upper(self: _Pipeline[_InT, str]) -> _Pipeline[_InT, str]:
  222. return self.transform(str.upper)
  223. def str_title(self: _Pipeline[_InT, str]) -> _Pipeline[_InT, str]:
  224. return self.transform(str.title)
  225. def str_strip(self: _Pipeline[_InT, str]) -> _Pipeline[_InT, str]:
  226. return self.transform(str.strip)
  227. def str_pattern(self: _Pipeline[_InT, str], pattern: str) -> _Pipeline[_InT, str]:
  228. return self.constrain(re.compile(pattern))
  229. def str_contains(self: _Pipeline[_InT, str], substring: str) -> _Pipeline[_InT, str]:
  230. return self.predicate(lambda v: substring in v)
  231. def str_starts_with(self: _Pipeline[_InT, str], prefix: str) -> _Pipeline[_InT, str]:
  232. return self.predicate(lambda v: v.startswith(prefix))
  233. def str_ends_with(self: _Pipeline[_InT, str], suffix: str) -> _Pipeline[_InT, str]:
  234. return self.predicate(lambda v: v.endswith(suffix))
  235. # operators
  236. def otherwise(self, other: _Pipeline[_OtherIn, _OtherOut]) -> _Pipeline[_InT | _OtherIn, _OutT | _OtherOut]:
  237. """Combine two validation chains, returning the result of the first chain if it succeeds, and the second chain if it fails."""
  238. return _Pipeline((_PipelineOr(self, other),))
  239. __or__ = otherwise
  240. def then(self, other: _Pipeline[_OutT, _OtherOut]) -> _Pipeline[_InT, _OtherOut]:
  241. """Pipe the result of one validation chain into another."""
  242. return _Pipeline((_PipelineAnd(self, other),))
  243. __and__ = then
  244. def __get_pydantic_core_schema__(self, source_type: Any, handler: GetCoreSchemaHandler) -> cs.CoreSchema:
  245. queue = deque(self._steps)
  246. s = None
  247. while queue:
  248. step = queue.popleft()
  249. s = _apply_step(step, s, handler, source_type)
  250. s = s or cs.any_schema()
  251. return s
  252. def __supports_type__(self, _: _OutT) -> bool:
  253. raise NotImplementedError
  254. validate_as = _Pipeline[Any, Any](()).validate_as
  255. validate_as_deferred = _Pipeline[Any, Any](()).validate_as_deferred
  256. transform = _Pipeline[Any, Any]((_ValidateAs(_FieldTypeMarker),)).transform
  257. def _check_func(
  258. func: Callable[[Any], bool], predicate_err: str | Callable[[], str], s: cs.CoreSchema | None
  259. ) -> cs.CoreSchema:
  260. def handler(v: Any) -> Any:
  261. if func(v):
  262. return v
  263. raise ValueError(f'Expected {predicate_err if isinstance(predicate_err, str) else predicate_err()}')
  264. if s is None:
  265. return cs.no_info_plain_validator_function(handler)
  266. else:
  267. return cs.no_info_after_validator_function(handler, s)
  268. def _apply_step(step: _Step, s: cs.CoreSchema | None, handler: GetCoreSchemaHandler, source_type: Any) -> cs.CoreSchema:
  269. if isinstance(step, _ValidateAs):
  270. s = _apply_parse(s, step.tp, step.strict, handler, source_type)
  271. elif isinstance(step, _ValidateAsDefer):
  272. s = _apply_parse(s, step.tp, False, handler, source_type)
  273. elif isinstance(step, _Transform):
  274. s = _apply_transform(s, step.func, handler)
  275. elif isinstance(step, _Constraint):
  276. s = _apply_constraint(s, step.constraint)
  277. elif isinstance(step, _PipelineOr):
  278. s = cs.union_schema([handler(step.left), handler(step.right)])
  279. else:
  280. assert isinstance(step, _PipelineAnd)
  281. s = cs.chain_schema([handler(step.left), handler(step.right)])
  282. return s
  283. def _apply_parse(
  284. s: cs.CoreSchema | None,
  285. tp: type[Any],
  286. strict: bool,
  287. handler: GetCoreSchemaHandler,
  288. source_type: Any,
  289. ) -> cs.CoreSchema:
  290. if tp is _FieldTypeMarker:
  291. return cs.chain_schema([s, handler(source_type)]) if s else handler(source_type)
  292. if strict:
  293. tp = Annotated[tp, Strict()] # type: ignore
  294. if s and s['type'] == 'any':
  295. return handler(tp)
  296. else:
  297. return cs.chain_schema([s, handler(tp)]) if s else handler(tp)
  298. def _apply_transform(
  299. s: cs.CoreSchema | None, func: Callable[[Any], Any], handler: GetCoreSchemaHandler
  300. ) -> cs.CoreSchema:
  301. if s is None:
  302. return cs.no_info_plain_validator_function(func)
  303. if s['type'] == 'str':
  304. if func is str.strip:
  305. s = s.copy()
  306. s['strip_whitespace'] = True
  307. return s
  308. elif func is str.lower:
  309. s = s.copy()
  310. s['to_lower'] = True
  311. return s
  312. elif func is str.upper:
  313. s = s.copy()
  314. s['to_upper'] = True
  315. return s
  316. return cs.no_info_after_validator_function(func, s)
  317. def _apply_constraint( # noqa: C901
  318. s: cs.CoreSchema | None, constraint: _ConstraintAnnotation
  319. ) -> cs.CoreSchema:
  320. """Apply a single constraint to a schema."""
  321. if isinstance(constraint, annotated_types.Gt):
  322. gt = constraint.gt
  323. if s and s['type'] in {'int', 'float', 'decimal'}:
  324. s = s.copy()
  325. if s['type'] == 'int' and isinstance(gt, int):
  326. s['gt'] = gt
  327. elif s['type'] == 'float' and isinstance(gt, float):
  328. s['gt'] = gt
  329. elif s['type'] == 'decimal' and isinstance(gt, Decimal):
  330. s['gt'] = gt
  331. else:
  332. def check_gt(v: Any) -> bool:
  333. return v > gt
  334. s = _check_func(check_gt, f'> {gt}', s)
  335. elif isinstance(constraint, annotated_types.Ge):
  336. ge = constraint.ge
  337. if s and s['type'] in {'int', 'float', 'decimal'}:
  338. s = s.copy()
  339. if s['type'] == 'int' and isinstance(ge, int):
  340. s['ge'] = ge
  341. elif s['type'] == 'float' and isinstance(ge, float):
  342. s['ge'] = ge
  343. elif s['type'] == 'decimal' and isinstance(ge, Decimal):
  344. s['ge'] = ge
  345. def check_ge(v: Any) -> bool:
  346. return v >= ge
  347. s = _check_func(check_ge, f'>= {ge}', s)
  348. elif isinstance(constraint, annotated_types.Lt):
  349. lt = constraint.lt
  350. if s and s['type'] in {'int', 'float', 'decimal'}:
  351. s = s.copy()
  352. if s['type'] == 'int' and isinstance(lt, int):
  353. s['lt'] = lt
  354. elif s['type'] == 'float' and isinstance(lt, float):
  355. s['lt'] = lt
  356. elif s['type'] == 'decimal' and isinstance(lt, Decimal):
  357. s['lt'] = lt
  358. def check_lt(v: Any) -> bool:
  359. return v < lt
  360. s = _check_func(check_lt, f'< {lt}', s)
  361. elif isinstance(constraint, annotated_types.Le):
  362. le = constraint.le
  363. if s and s['type'] in {'int', 'float', 'decimal'}:
  364. s = s.copy()
  365. if s['type'] == 'int' and isinstance(le, int):
  366. s['le'] = le
  367. elif s['type'] == 'float' and isinstance(le, float):
  368. s['le'] = le
  369. elif s['type'] == 'decimal' and isinstance(le, Decimal):
  370. s['le'] = le
  371. def check_le(v: Any) -> bool:
  372. return v <= le
  373. s = _check_func(check_le, f'<= {le}', s)
  374. elif isinstance(constraint, annotated_types.Len):
  375. min_len = constraint.min_length
  376. max_len = constraint.max_length
  377. if s and s['type'] in {'str', 'list', 'tuple', 'set', 'frozenset', 'dict'}:
  378. assert (
  379. s['type'] == 'str'
  380. or s['type'] == 'list'
  381. or s['type'] == 'tuple'
  382. or s['type'] == 'set'
  383. or s['type'] == 'dict'
  384. or s['type'] == 'frozenset'
  385. )
  386. s = s.copy()
  387. if min_len != 0:
  388. s['min_length'] = min_len
  389. if max_len is not None:
  390. s['max_length'] = max_len
  391. def check_len(v: Any) -> bool:
  392. if max_len is not None:
  393. return (min_len <= len(v)) and (len(v) <= max_len)
  394. return min_len <= len(v)
  395. s = _check_func(check_len, f'length >= {min_len} and length <= {max_len}', s)
  396. elif isinstance(constraint, annotated_types.MultipleOf):
  397. multiple_of = constraint.multiple_of
  398. if s and s['type'] in {'int', 'float', 'decimal'}:
  399. s = s.copy()
  400. if s['type'] == 'int' and isinstance(multiple_of, int):
  401. s['multiple_of'] = multiple_of
  402. elif s['type'] == 'float' and isinstance(multiple_of, float):
  403. s['multiple_of'] = multiple_of
  404. elif s['type'] == 'decimal' and isinstance(multiple_of, Decimal):
  405. s['multiple_of'] = multiple_of
  406. def check_multiple_of(v: Any) -> bool:
  407. return v % multiple_of == 0
  408. s = _check_func(check_multiple_of, f'% {multiple_of} == 0', s)
  409. elif isinstance(constraint, annotated_types.Timezone):
  410. tz = constraint.tz
  411. if tz is ...:
  412. if s and s['type'] == 'datetime':
  413. s = s.copy()
  414. s['tz_constraint'] = 'aware'
  415. else:
  416. def check_tz_aware(v: object) -> bool:
  417. assert isinstance(v, datetime.datetime)
  418. return v.tzinfo is not None
  419. s = _check_func(check_tz_aware, 'timezone aware', s)
  420. elif tz is None:
  421. if s and s['type'] == 'datetime':
  422. s = s.copy()
  423. s['tz_constraint'] = 'naive'
  424. else:
  425. def check_tz_naive(v: object) -> bool:
  426. assert isinstance(v, datetime.datetime)
  427. return v.tzinfo is None
  428. s = _check_func(check_tz_naive, 'timezone naive', s)
  429. else:
  430. raise NotImplementedError('Constraining to a specific timezone is not yet supported')
  431. elif isinstance(constraint, annotated_types.Interval):
  432. if constraint.ge:
  433. s = _apply_constraint(s, annotated_types.Ge(constraint.ge))
  434. if constraint.gt:
  435. s = _apply_constraint(s, annotated_types.Gt(constraint.gt))
  436. if constraint.le:
  437. s = _apply_constraint(s, annotated_types.Le(constraint.le))
  438. if constraint.lt:
  439. s = _apply_constraint(s, annotated_types.Lt(constraint.lt))
  440. assert s is not None
  441. elif isinstance(constraint, annotated_types.Predicate):
  442. func = constraint.func
  443. # Same logic as in `_known_annotated_metadata.apply_known_metadata()`:
  444. predicate_name = f'{func.__qualname__!r} ' if hasattr(func, '__qualname__') else ''
  445. def predicate_func(v: Any) -> Any:
  446. if not func(v):
  447. raise PydanticCustomError(
  448. 'predicate_failed',
  449. f'Predicate {predicate_name}failed', # pyright: ignore[reportArgumentType]
  450. )
  451. return v
  452. if s is None:
  453. s = cs.no_info_plain_validator_function(predicate_func)
  454. else:
  455. s = cs.no_info_after_validator_function(predicate_func, s)
  456. elif isinstance(constraint, _NotEq):
  457. value = constraint.value
  458. def check_not_eq(v: Any) -> bool:
  459. return operator.__ne__(v, value)
  460. s = _check_func(check_not_eq, f'!= {value}', s)
  461. elif isinstance(constraint, _Eq):
  462. value = constraint.value
  463. def check_eq(v: Any) -> bool:
  464. return operator.__eq__(v, value)
  465. s = _check_func(check_eq, f'== {value}', s)
  466. elif isinstance(constraint, _In):
  467. values = constraint.values
  468. def check_in(v: Any) -> bool:
  469. return operator.__contains__(values, v)
  470. s = _check_func(check_in, f'in {values}', s)
  471. elif isinstance(constraint, _NotIn):
  472. values = constraint.values
  473. def check_not_in(v: Any) -> bool:
  474. return operator.__not__(operator.__contains__(values, v))
  475. s = _check_func(check_not_in, f'not in {values}', s)
  476. else:
  477. assert isinstance(constraint, Pattern)
  478. if s and s['type'] == 'str':
  479. s = s.copy()
  480. s['pattern'] = constraint.pattern
  481. else:
  482. def check_pattern(v: object) -> bool:
  483. assert isinstance(v, str)
  484. return constraint.match(v) is not None
  485. s = _check_func(check_pattern, f'~ {constraint.pattern}', s)
  486. return s
  487. class _SupportsRange(annotated_types.SupportsLe, annotated_types.SupportsGe, Protocol):
  488. pass
  489. class _SupportsLen(Protocol):
  490. def __len__(self) -> int: ...
  491. _NewOutGt = TypeVar('_NewOutGt', bound=annotated_types.SupportsGt)
  492. _NewOutGe = TypeVar('_NewOutGe', bound=annotated_types.SupportsGe)
  493. _NewOutLt = TypeVar('_NewOutLt', bound=annotated_types.SupportsLt)
  494. _NewOutLe = TypeVar('_NewOutLe', bound=annotated_types.SupportsLe)
  495. _NewOutLen = TypeVar('_NewOutLen', bound=_SupportsLen)
  496. _NewOutDiv = TypeVar('_NewOutDiv', bound=annotated_types.SupportsDiv)
  497. _NewOutMod = TypeVar('_NewOutMod', bound=annotated_types.SupportsMod)
  498. _NewOutDatetime = TypeVar('_NewOutDatetime', bound=datetime.datetime)
  499. _NewOutInterval = TypeVar('_NewOutInterval', bound=_SupportsRange)
  500. _OtherIn = TypeVar('_OtherIn')
  501. _OtherOut = TypeVar('_OtherOut')