Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.
 
 
 
 

668 rindas
23 KiB

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