Coverage for pydantic / experimental / pipeline.py: 95.49%

323 statements  

« prev     ^ index     » next       coverage.py v7.13.5, created at 2026-11-21 11:56 +0000

1"""Experimental pipeline API functionality. Be careful with this API, it's subject to change.""" 

2 

3from __future__ import annotations 1gabhijkcdlmnoefpqr

4 

5import datetime 1gabhijkcdlmnoefpqr

6import operator 1gabhijkcdlmnoefpqr

7import re 1gabhijkcdlmnoefpqr

8from collections import deque 1gabhijkcdlmnoefpqr

9from collections.abc import Callable, Container 1gabhijkcdlmnoefpqr

10from dataclasses import dataclass 1gabhijkcdlmnoefpqr

11from functools import cached_property, partial 1gabhijkcdlmnoefpqr

12from re import Pattern 1gabhijkcdlmnoefpqr

13from types import EllipsisType 1gabhijkcdlmnoefpqr

14from typing import TYPE_CHECKING, Annotated, Any, Generic, Protocol, TypeAlias, TypeVar, overload 1gabhijkcdlmnoefpqr

15 

16import annotated_types 1gabhijkcdlmnoefpqr

17from typing_extensions import TypeForm 1gabhijkcdlmnoefpqr

18 

19if TYPE_CHECKING: 1gabhijkcdlmnoefpqr

20 from pydantic import GetCoreSchemaHandler 

21 

22from pydantic_core import PydanticCustomError 1gabhijkcdlmnoefpqr

23from pydantic_core import core_schema as cs 1gabhijkcdlmnoefpqr

24 

25from pydantic import Strict 1gabhijkcdlmnoefpqr

26 

27__all__ = ['validate_as', 'validate_as_deferred', 'transform'] 1gabhijkcdlmnoefpqr

28 

29 

30@dataclass(frozen=True, slots=True) 1gabhijkcdlmnoefpqr

31class _ValidateAs: 1gabhijkcdlmnoefpqr

32 tp: TypeForm[Any] 1gabhijkcdlmnoefpqr

33 strict: bool = False 1gabhijkcdlmnoefpqr

34 

35 

36@dataclass 1gabhijkcdlmnoefpqr

37class _ValidateAsDefer: 1gabhijkcdlmnoefpqr

38 func: Callable[[], TypeForm[Any]] 1gabhijkcdlmnoefpqr

39 

40 @cached_property 1gabhijkcdlmnoefpqr

41 def tp(self) -> TypeForm[Any]: 1gabhijkcdlmnoefpqr

42 return self.func() 

43 

44 

45@dataclass(frozen=True, slots=True) 1gabhijkcdlmnoefpqr

46class _Transform: 1gabhijkcdlmnoefpqr

47 func: Callable[[Any], Any] 1gabhijkcdlmnoefpqr

48 

49 

50@dataclass(frozen=True, slots=True) 1gabhijkcdlmnoefpqr

51class _PipelineOr: 1gabhijkcdlmnoefpqr

52 left: _Pipeline[Any, Any] 1gabhijkcdlmnoefpqr

53 right: _Pipeline[Any, Any] 1gabhijkcdlmnoefpqr

54 

55 

56@dataclass(frozen=True, slots=True) 1gabhijkcdlmnoefpqr

57class _PipelineAnd: 1gabhijkcdlmnoefpqr

58 left: _Pipeline[Any, Any] 1gabhijkcdlmnoefpqr

59 right: _Pipeline[Any, Any] 1gabhijkcdlmnoefpqr

60 

61 

62@dataclass(frozen=True, slots=True) 1gabhijkcdlmnoefpqr

63class _Eq: 1gabhijkcdlmnoefpqr

64 value: Any 1gabhijkcdlmnoefpqr

65 

66 

67@dataclass(frozen=True, slots=True) 1gabhijkcdlmnoefpqr

68class _NotEq: 1gabhijkcdlmnoefpqr

69 value: Any 1gabhijkcdlmnoefpqr

70 

71 

72@dataclass(frozen=True, slots=True) 1gabhijkcdlmnoefpqr

73class _In: 1gabhijkcdlmnoefpqr

74 values: Container[Any] 1gabhijkcdlmnoefpqr

75 

76 

77@dataclass(frozen=True, slots=True) 1gabhijkcdlmnoefpqr

78class _NotIn: 1gabhijkcdlmnoefpqr

79 values: Container[Any] 1gabhijkcdlmnoefpqr

80 

81 

82_ConstraintAnnotation: TypeAlias = ( 1gabhijkcdlmnoefpqr

83 annotated_types.Le 

84 | annotated_types.Ge 

85 | annotated_types.Lt 

86 | annotated_types.Gt 

87 | annotated_types.Len 

88 | annotated_types.MultipleOf 

89 | annotated_types.Timezone 

90 | annotated_types.Interval 

91 | annotated_types.Predicate 

92 | 

93 # common predicates not included in annotated_types 

94 _Eq 

95 | _NotEq 

96 | _In 

97 | _NotIn 

98 | 

99 # regular expressions 

100 Pattern[str] 

101) 

102 

103 

104@dataclass(frozen=True, slots=True) 1gabhijkcdlmnoefpqr

105class _Constraint: 1gabhijkcdlmnoefpqr

106 constraint: _ConstraintAnnotation 1gabhijkcdlmnoefpqr

107 

108 

109_Step: TypeAlias = _ValidateAs | _ValidateAsDefer | _Transform | _PipelineOr | _PipelineAnd | _Constraint 1gabhijkcdlmnoefpqr

110 

111_InT = TypeVar('_InT') 1gabhijkcdlmnoefpqr

112_OutT = TypeVar('_OutT') 1gabhijkcdlmnoefpqr

113_NewOutT = TypeVar('_NewOutT') 1gabhijkcdlmnoefpqr

114 

115 

116class _FieldTypeMarker: 1gabhijkcdlmnoefpqr

117 pass 1gabhijkcdlmnoefpqr

118 

119 

120# TODO: ultimately, make this public, see https://github.com/pydantic/pydantic/pull/9459#discussion_r1628197626 

121# Also, make this frozen eventually, but that doesn't work right now because of the generic base 

122# Which attempts to modify __orig_base__ and such. 

123# We could go with a manual freeze, but that seems overkill for now. 

124@dataclass(slots=True) 1gabhijkcdlmnoefpqr

125class _Pipeline(Generic[_InT, _OutT]): 1gabhijkcdlmnoefpqr

126 """Abstract representation of a chain of validation, transformation, and parsing steps.""" 

127 

128 _steps: tuple[_Step, ...] 1gabhijkcdlmnoefpqr

129 

130 def transform( 1gabhijkcdlmnoefpqr

131 self, 

132 func: Callable[[_OutT], _NewOutT], 

133 ) -> _Pipeline[_InT, _NewOutT]: 

134 """Transform the output of the previous step. 

135 

136 If used as the first step in a pipeline, the type of the field is used. 

137 That is, the transformation is applied to after the value is parsed to the field's type. 

138 """ 

139 return _Pipeline[_InT, _NewOutT](self._steps + (_Transform(func),)) 1gabhijkcdlmnoefpqr

140 

141 @overload 1gabhijkcdlmnoefpqr

142 def validate_as(self, tp: TypeForm[_NewOutT], *, strict: bool = False) -> _Pipeline[_InT, _NewOutT]: ... 1gabhijkcdlmnoefpqr

143 

144 @overload 1gabhijkcdlmnoefpqr

145 def validate_as( 1gabhijkcdlmnoefpqr

146 self, 

147 tp: EllipsisType, 1abcdef

148 *, 

149 strict: bool = False, 1gabhijkcdlmnoefpqr

150 ) -> _Pipeline[_InT, Any]: ... 1abcdef

151 

152 def validate_as(self, tp: TypeForm[_NewOutT] | EllipsisType, *, strict: bool = False) -> _Pipeline[_InT, Any]: # type: ignore 1gabhijkcdlmnoefpqr

153 """Validate / parse the input into a new type. 

154 

155 If no type is provided, the type of the field is used. 

156 

157 Types are parsed in Pydantic's `lax` mode by default, 

158 but you can enable `strict` mode by passing `strict=True`. 

159 """ 

160 if isinstance(tp, EllipsisType): 1gabhijkcdlmnoefpqr

161 return _Pipeline[_InT, Any](self._steps + (_ValidateAs(_FieldTypeMarker, strict=strict),)) 1gabhijkcdlmnoefpqr

162 return _Pipeline[_InT, _NewOutT](self._steps + (_ValidateAs(tp, strict=strict),)) 1gabhijkcdlmnoefpqr

163 

164 def validate_as_deferred(self, func: Callable[[], type[_NewOutT]]) -> _Pipeline[_InT, _NewOutT]: 1gabhijkcdlmnoefpqr

165 """Parse the input into a new type, deferring resolution of the type until the current class 

166 is fully defined. 

167 

168 This is useful when you need to reference the class in it's own type annotations. 

169 """ 

170 return _Pipeline[_InT, _NewOutT](self._steps + (_ValidateAsDefer(func),)) 

171 

172 # constraints 

173 @overload 1gabhijkcdlmnoefpqr

174 def constrain(self: _Pipeline[_InT, _NewOutGe], constraint: annotated_types.Ge) -> _Pipeline[_InT, _NewOutGe]: ... 1gabhijkcdlmnoefpqr

175 

176 @overload 1gabhijkcdlmnoefpqr

177 def constrain(self: _Pipeline[_InT, _NewOutGt], constraint: annotated_types.Gt) -> _Pipeline[_InT, _NewOutGt]: ... 1gabhijkcdlmnoefpqr

178 

179 @overload 1gabhijkcdlmnoefpqr

180 def constrain(self: _Pipeline[_InT, _NewOutLe], constraint: annotated_types.Le) -> _Pipeline[_InT, _NewOutLe]: ... 1gabhijkcdlmnoefpqr

181 

182 @overload 1gabhijkcdlmnoefpqr

183 def constrain(self: _Pipeline[_InT, _NewOutLt], constraint: annotated_types.Lt) -> _Pipeline[_InT, _NewOutLt]: ... 1gabhijkcdlmnoefpqr

184 

185 @overload 1gabhijkcdlmnoefpqr

186 def constrain( 1gabhijkcdlmnoefpqr

187 self: _Pipeline[_InT, _NewOutLen], constraint: annotated_types.Len 1abcdef

188 ) -> _Pipeline[_InT, _NewOutLen]: ... 1abcdef

189 

190 @overload 1gabhijkcdlmnoefpqr

191 def constrain( 1gabhijkcdlmnoefpqr

192 self: _Pipeline[_InT, _NewOutT], constraint: annotated_types.MultipleOf 1abcdef

193 ) -> _Pipeline[_InT, _NewOutT]: ... 1abcdef

194 

195 @overload 1gabhijkcdlmnoefpqr

196 def constrain( 1gabhijkcdlmnoefpqr

197 self: _Pipeline[_InT, _NewOutDatetime], constraint: annotated_types.Timezone 1abcdef

198 ) -> _Pipeline[_InT, _NewOutDatetime]: ... 1abcdef

199 

200 @overload 1gabhijkcdlmnoefpqr

201 def constrain(self: _Pipeline[_InT, _OutT], constraint: annotated_types.Predicate) -> _Pipeline[_InT, _OutT]: ... 1gabhijkcdlmnoefpqr

202 

203 @overload 1gabhijkcdlmnoefpqr

204 def constrain( 1gabhijkcdlmnoefpqr

205 self: _Pipeline[_InT, _NewOutInterval], constraint: annotated_types.Interval 1abcdef

206 ) -> _Pipeline[_InT, _NewOutInterval]: ... 1abcdef

207 

208 @overload 1gabhijkcdlmnoefpqr

209 def constrain(self: _Pipeline[_InT, _OutT], constraint: _Eq) -> _Pipeline[_InT, _OutT]: ... 1gabhijkcdlmnoefpqr

210 

211 @overload 1gabhijkcdlmnoefpqr

212 def constrain(self: _Pipeline[_InT, _OutT], constraint: _NotEq) -> _Pipeline[_InT, _OutT]: ... 1gabhijkcdlmnoefpqr

213 

214 @overload 1gabhijkcdlmnoefpqr

215 def constrain(self: _Pipeline[_InT, _OutT], constraint: _In) -> _Pipeline[_InT, _OutT]: ... 1gabhijkcdlmnoefpqr

216 

217 @overload 1gabhijkcdlmnoefpqr

218 def constrain(self: _Pipeline[_InT, _OutT], constraint: _NotIn) -> _Pipeline[_InT, _OutT]: ... 1gabhijkcdlmnoefpqr

219 

220 @overload 1gabhijkcdlmnoefpqr

221 def constrain(self: _Pipeline[_InT, _NewOutT], constraint: Pattern[str]) -> _Pipeline[_InT, _NewOutT]: ... 1gabhijkcdlmnoefpqr

222 

223 def constrain(self, constraint: _ConstraintAnnotation) -> Any: 1gabhijkcdlmnoefpqr

224 """Constrain a value to meet a certain condition. 

225 

226 We support most conditions from `annotated_types`, as well as regular expressions. 

227 

228 Most of the time you'll be calling a shortcut method like `gt`, `lt`, `len`, etc 

229 so you don't need to call this directly. 

230 """ 

231 return _Pipeline[_InT, _OutT](self._steps + (_Constraint(constraint),)) 1gabhijkcdlmnoefpqr

232 

233 def predicate(self: _Pipeline[_InT, _NewOutT], func: Callable[[_NewOutT], bool]) -> _Pipeline[_InT, _NewOutT]: 1gabhijkcdlmnoefpqr

234 """Constrain a value to meet a certain predicate.""" 

235 return self.constrain(annotated_types.Predicate(func)) 1gabhijkcdlmnoefpqr

236 

237 def gt(self: _Pipeline[_InT, _NewOutGt], gt: _NewOutGt) -> _Pipeline[_InT, _NewOutGt]: 1gabhijkcdlmnoefpqr

238 """Constrain a value to be greater than a certain value.""" 

239 return self.constrain(annotated_types.Gt(gt)) 1gabhijkcdlmnoefpqr

240 

241 def lt(self: _Pipeline[_InT, _NewOutLt], lt: _NewOutLt) -> _Pipeline[_InT, _NewOutLt]: 1gabhijkcdlmnoefpqr

242 """Constrain a value to be less than a certain value.""" 

243 return self.constrain(annotated_types.Lt(lt)) 1gabhijkcdlmnoefpqr

244 

245 def ge(self: _Pipeline[_InT, _NewOutGe], ge: _NewOutGe) -> _Pipeline[_InT, _NewOutGe]: 1gabhijkcdlmnoefpqr

246 """Constrain a value to be greater than or equal to a certain value.""" 

247 return self.constrain(annotated_types.Ge(ge)) 1gabhijkcdlmnoefpqr

248 

249 def le(self: _Pipeline[_InT, _NewOutLe], le: _NewOutLe) -> _Pipeline[_InT, _NewOutLe]: 1gabhijkcdlmnoefpqr

250 """Constrain a value to be less than or equal to a certain value.""" 

251 return self.constrain(annotated_types.Le(le)) 1gabhijkcdlmnoefpqr

252 

253 def len(self: _Pipeline[_InT, _NewOutLen], min_len: int, max_len: int | None = None) -> _Pipeline[_InT, _NewOutLen]: 1gabhijkcdlmnoefpqr

254 """Constrain a value to have a certain length.""" 

255 return self.constrain(annotated_types.Len(min_len, max_len)) 1gabhijkcdlmnoefpqr

256 

257 @overload 1gabhijkcdlmnoefpqr

258 def multiple_of(self: _Pipeline[_InT, _NewOutDiv], multiple_of: _NewOutDiv) -> _Pipeline[_InT, _NewOutDiv]: ... 1gabhijkcdlmnoefpqr

259 

260 @overload 1gabhijkcdlmnoefpqr

261 def multiple_of(self: _Pipeline[_InT, _NewOutMod], multiple_of: _NewOutMod) -> _Pipeline[_InT, _NewOutMod]: ... 1gabhijkcdlmnoefpqr

262 

263 def multiple_of(self: _Pipeline[_InT, Any], multiple_of: Any) -> _Pipeline[_InT, Any]: 1gabhijkcdlmnoefpqr

264 """Constrain a value to be a multiple of a certain number.""" 

265 return self.constrain(annotated_types.MultipleOf(multiple_of)) 1gabhijkcdlmnoefpqr

266 

267 def eq(self: _Pipeline[_InT, _OutT], value: _OutT) -> _Pipeline[_InT, _OutT]: 1gabhijkcdlmnoefpqr

268 """Constrain a value to be equal to a certain value.""" 

269 return self.constrain(_Eq(value)) 1gabhijkcdlmnoefpqr

270 

271 def not_eq(self: _Pipeline[_InT, _OutT], value: _OutT) -> _Pipeline[_InT, _OutT]: 1gabhijkcdlmnoefpqr

272 """Constrain a value to not be equal to a certain value.""" 

273 return self.constrain(_NotEq(value)) 1gabhijkcdlmnoefpqr

274 

275 def in_(self: _Pipeline[_InT, _OutT], values: Container[_OutT]) -> _Pipeline[_InT, _OutT]: 1gabhijkcdlmnoefpqr

276 """Constrain a value to be in a certain set.""" 

277 return self.constrain(_In(values)) 1gabhijkcdlmnoefpqr

278 

279 def not_in(self: _Pipeline[_InT, _OutT], values: Container[_OutT]) -> _Pipeline[_InT, _OutT]: 1gabhijkcdlmnoefpqr

280 """Constrain a value to not be in a certain set.""" 

281 return self.constrain(_NotIn(values)) 1gabhijkcdlmnoefpqr

282 

283 # timezone methods 

284 def datetime_tz_naive(self: _Pipeline[_InT, datetime.datetime]) -> _Pipeline[_InT, datetime.datetime]: 1gabhijkcdlmnoefpqr

285 """Constrain a datetime value to be timezone-naive (i.e. have no tzinfo).""" 

286 return self.constrain(annotated_types.Timezone(None)) 1gabhijkcdlmnoefpqr

287 

288 def datetime_tz_aware(self: _Pipeline[_InT, datetime.datetime]) -> _Pipeline[_InT, datetime.datetime]: 1gabhijkcdlmnoefpqr

289 """Constrain a datetime value to be timezone-aware (i.e. have a non-None tzinfo).""" 

290 return self.constrain(annotated_types.Timezone(...)) 1gabhijkcdlmnoefpqr

291 

292 def datetime_tz( 1gabhijkcdlmnoefpqr

293 self: _Pipeline[_InT, datetime.datetime], tz: datetime.tzinfo 

294 ) -> _Pipeline[_InT, datetime.datetime]: 

295 """Constrain a datetime value to have a specific timezone. 

296 

297 Args: 

298 tz: The required timezone. 

299 """ 

300 return self.constrain(annotated_types.Timezone(tz)) # type: ignore 

301 

302 def datetime_with_tz( 1gabhijkcdlmnoefpqr

303 self: _Pipeline[_InT, datetime.datetime], tz: datetime.tzinfo | None 

304 ) -> _Pipeline[_InT, datetime.datetime]: 

305 """Transform a datetime value by replacing its timezone with the given value. 

306 

307 Unlike `datetime_tz()`, this does not validate the existing timezone, it 

308 unconditionally sets [`tzinfo`][datetime.datetime.tzinfo] to `tz`. 

309 

310 Args: 

311 tz: The timezone to attach to the datetime, or `None` to make it naive. 

312 """ 

313 return self.transform(partial(datetime.datetime.replace, tzinfo=tz)) 

314 

315 # string methods 

316 def str_lower(self: _Pipeline[_InT, str]) -> _Pipeline[_InT, str]: 1gabhijkcdlmnoefpqr

317 """Transform a string value to [lowercase][str.lower].""" 

318 return self.transform(str.lower) 1gabhijkcdlmnoefpqr

319 

320 def str_upper(self: _Pipeline[_InT, str]) -> _Pipeline[_InT, str]: 1gabhijkcdlmnoefpqr

321 """Transform a string value to [uppercase][str.upper].""" 

322 return self.transform(str.upper) 1gabhijkcdlmnoefpqr

323 

324 def str_title(self: _Pipeline[_InT, str]) -> _Pipeline[_InT, str]: 1gabhijkcdlmnoefpqr

325 """Transform a string value to [title case][str.title].""" 

326 return self.transform(str.title) 1gabhijkcdlmnoefpqr

327 

328 def str_strip(self: _Pipeline[_InT, str]) -> _Pipeline[_InT, str]: 1gabhijkcdlmnoefpqr

329 """Strip leading and trailing whitespace from a string value.""" 

330 return self.transform(str.strip) 1gabhijkcdlmnoefpqr

331 

332 def str_pattern(self: _Pipeline[_InT, str], pattern: str) -> _Pipeline[_InT, str]: 1gabhijkcdlmnoefpqr

333 """Constrain a string value to match a regular expression pattern. 

334 

335 Args: 

336 pattern: The regular expression pattern the string must match. 

337 """ 

338 return self.constrain(re.compile(pattern)) 1gabhijkcdlmnoefpqr

339 

340 def str_contains(self: _Pipeline[_InT, str], substring: str) -> _Pipeline[_InT, str]: 1gabhijkcdlmnoefpqr

341 """Constrain a string value to contain a given substring. 

342 

343 Args: 

344 substring: The substring that must be present in the string. 

345 """ 

346 return self.predicate(lambda v: substring in v) 1gabhijkcdlmnoefpqr

347 

348 def str_starts_with(self: _Pipeline[_InT, str], prefix: str) -> _Pipeline[_InT, str]: 1gabhijkcdlmnoefpqr

349 """Constrain a string value to start with a given prefix. 

350 

351 Args: 

352 prefix: The prefix the string must start with. 

353 """ 

354 return self.predicate(lambda v: v.startswith(prefix)) 1gabhijkcdlmnoefpqr

355 

356 def str_ends_with(self: _Pipeline[_InT, str], suffix: str) -> _Pipeline[_InT, str]: 1gabhijkcdlmnoefpqr

357 """Constrain a string value to end with a given suffix. 

358 

359 Args: 

360 suffix: The suffix the string must end with. 

361 """ 

362 return self.predicate(lambda v: v.endswith(suffix)) 1gabhijkcdlmnoefpqr

363 

364 # operators 

365 def otherwise(self, other: _Pipeline[_OtherIn, _OtherOut]) -> _Pipeline[_InT | _OtherIn, _OutT | _OtherOut]: 1gabhijkcdlmnoefpqr

366 """Combine two validation chains, returning the result of the first chain if it succeeds, and the second chain if it fails.""" 

367 return _Pipeline((_PipelineOr(self, other),)) 1gabhijkcdlmnoefpqr

368 

369 __or__ = otherwise 1gabhijkcdlmnoefpqr

370 

371 def then(self, other: _Pipeline[_OutT, _OtherOut]) -> _Pipeline[_InT, _OtherOut]: 1gabhijkcdlmnoefpqr

372 """Pipe the result of one validation chain into another.""" 

373 return _Pipeline((_PipelineAnd(self, other),)) 1gabhijkcdlmnoefpqr

374 

375 __and__ = then 1gabhijkcdlmnoefpqr

376 

377 def __get_pydantic_core_schema__(self, source_type: Any, handler: GetCoreSchemaHandler) -> cs.CoreSchema: 1gabhijkcdlmnoefpqr

378 return self._apply_pipeline(handler, source_type) 1gabhijkcdlmnoefpqr

379 

380 def _apply_pipeline(self, handler: GetCoreSchemaHandler, source_type: Any) -> cs.CoreSchema: 1gabhijkcdlmnoefpqr

381 queue = deque(self._steps) 1gabhijkcdlmnoefpqr

382 

383 s = None 1gabhijkcdlmnoefpqr

384 

385 while queue: 1gabhijkcdlmnoefpqr

386 step = queue.popleft() 1gabhijkcdlmnoefpqr

387 s = _apply_step(step, s, handler, source_type) 1gabhijkcdlmnoefpqr

388 

389 s = s or cs.any_schema() 1gabhijkcdlmnoefpqr

390 return s 1gabhijkcdlmnoefpqr

391 

392 def __supports_type__(self, _: _OutT) -> bool: 1gabhijkcdlmnoefpqr

393 raise NotImplementedError 

394 

395 

396validate_as = _Pipeline[Any, Any](()).validate_as 1gabhijkcdlmnoefpqr

397validate_as_deferred = _Pipeline[Any, Any](()).validate_as_deferred 1gabhijkcdlmnoefpqr

398transform = _Pipeline[Any, Any]((_ValidateAs(_FieldTypeMarker),)).transform 1gabhijkcdlmnoefpqr

399 

400 

401def _check_func( 1gabhijkcdlmnoefpqr

402 func: Callable[[Any], bool], predicate_err: str | Callable[[], str], s: cs.CoreSchema | None 

403) -> cs.CoreSchema: 

404 def handler(v: Any) -> Any: 1gabhijkcdlmnoefpqr

405 if func(v): 1gabhijkcdlmnoefpqr

406 return v 1gabhijkcdlmnoefpqr

407 raise ValueError(f'Expected {predicate_err if isinstance(predicate_err, str) else predicate_err()}') 1gabhijkcdlmnoefpqr

408 

409 if s is None: 409 ↛ 410line 409 didn't jump to line 410 because the condition on line 409 was never true1gabhijkcdlmnoefpqr

410 return cs.no_info_plain_validator_function(handler) 

411 else: 

412 return cs.no_info_after_validator_function(handler, s) 1gabhijkcdlmnoefpqr

413 

414 

415def _apply_step(step: _Step, s: cs.CoreSchema | None, handler: GetCoreSchemaHandler, source_type: Any) -> cs.CoreSchema: 1gabhijkcdlmnoefpqr

416 if isinstance(step, _ValidateAs): 1gabhijkcdlmnoefpqr

417 s = _apply_parse(s, step.tp, step.strict, handler, source_type) 1gabhijkcdlmnoefpqr

418 elif isinstance(step, _ValidateAsDefer): 418 ↛ 419line 418 didn't jump to line 419 because the condition on line 418 was never true1gabhijkcdlmnoefpqr

419 s = _apply_parse(s, step.tp, False, handler, source_type) 

420 elif isinstance(step, _Transform): 1gabhijkcdlmnoefpqr

421 s = _apply_transform(s, step.func, handler) 1gabhijkcdlmnoefpqr

422 elif isinstance(step, _Constraint): 1gabhijkcdlmnoefpqr

423 s = _apply_constraint(s, step.constraint) 1gabhijkcdlmnoefpqr

424 elif isinstance(step, _PipelineOr): 1gabhijkcdlmnoefpqr

425 s = cs.union_schema( 1gabhijkcdlmnoefpqr

426 [step.left._apply_pipeline(handler, source_type), step.right._apply_pipeline(handler, source_type)] 

427 ) 

428 else: 

429 assert isinstance(step, _PipelineAnd) 1gabhijkcdlmnoefpqr

430 s = cs.chain_schema( 1gabhijkcdlmnoefpqr

431 [step.left._apply_pipeline(handler, source_type), step.right._apply_pipeline(handler, source_type)] 

432 ) 

433 return s 1gabhijkcdlmnoefpqr

434 

435 

436def _apply_parse( 1gabhijkcdlmnoefpqr

437 s: cs.CoreSchema | None, 

438 tp: TypeForm[Any], 

439 strict: bool, 

440 handler: GetCoreSchemaHandler, 

441 source_type: Any, 

442) -> cs.CoreSchema: 

443 if tp is _FieldTypeMarker: 1gabhijkcdlmnoefpqr

444 return cs.chain_schema([s, handler(source_type)]) if s else handler(source_type) 1gabhijkcdlmnoefpqr

445 

446 if strict: 1gabhijkcdlmnoefpqr

447 tp = Annotated[tp, Strict()] # type: ignore 1gabhijkcdlmnoefpqr

448 

449 if s and s['type'] == 'any': 449 ↛ 450line 449 didn't jump to line 450 because the condition on line 449 was never true1gabhijkcdlmnoefpqr

450 return handler(tp) 

451 else: 

452 return cs.chain_schema([s, handler(tp)]) if s else handler(tp) 1gabhijkcdlmnoefpqr

453 

454 

455def _apply_transform( 1gabhijkcdlmnoefpqr

456 s: cs.CoreSchema | None, func: Callable[[Any], Any], handler: GetCoreSchemaHandler 

457) -> cs.CoreSchema: 

458 if s is None: 458 ↛ 459line 458 didn't jump to line 459 because the condition on line 458 was never true1gabhijkcdlmnoefpqr

459 return cs.no_info_plain_validator_function(func) 

460 

461 if s['type'] == 'str': 1gabhijkcdlmnoefpqr

462 if func is str.strip: 1gabhijkcdlmnoefpqr

463 s = s.copy() 1gabhijkcdlmnoefpqr

464 s['strip_whitespace'] = True 1gabhijkcdlmnoefpqr

465 return s 1gabhijkcdlmnoefpqr

466 elif func is str.lower: 1gabhijkcdlmnoefpqr

467 s = s.copy() 1gabhijkcdlmnoefpqr

468 s['to_lower'] = True 1gabhijkcdlmnoefpqr

469 return s 1gabhijkcdlmnoefpqr

470 elif func is str.upper: 1gabhijkcdlmnoefpqr

471 s = s.copy() 1gabhijkcdlmnoefpqr

472 s['to_upper'] = True 1gabhijkcdlmnoefpqr

473 return s 1gabhijkcdlmnoefpqr

474 

475 return cs.no_info_after_validator_function(func, s) 1gabhijkcdlmnoefpqr

476 

477 

478# Core schema types with native support for the `gt`/`ge`/`lt`/`le` constraints: 

479_ORDERING_SCHEMA_TYPES = frozenset({'int', 'float', 'decimal', 'fraction', 'date', 'time', 'datetime', 'timedelta'}) 1gabhijkcdlmnoefpqr

480# Core schema types with native support for the `min_length`/`max_length` constraints: 

481_LENGTH_SCHEMA_TYPES = frozenset( 1gabhijkcdlmnoefpqr

482 {'str', 'bytes', 'list', 'tuple', 'set', 'frozenset', 'dict', 'frozendict', 'ordered-dict', 'counter', 'generator'} 

483) 

484 

485 

486def _apply_constraint( # noqa: C901 1gabhijkcdlmnoefpqr

487 s: cs.CoreSchema | None, constraint: _ConstraintAnnotation 

488) -> cs.CoreSchema: 

489 """Apply a single constraint to a schema.""" 

490 # No casting of the constraints is necessary, as pydantic-core does it 

491 # when building the validator from the core schema: 

492 if isinstance(constraint, annotated_types.Gt): 1gabhijkcdlmnoefpqr

493 gt = constraint.gt 1gabhijkcdlmnoefpqr

494 if s and s['type'] in _ORDERING_SCHEMA_TYPES: 1gabhijkcdlmnoefpqr

495 s = s.copy() 1gabhijkcdlmnoefpqr

496 s['gt'] = gt # pyright: ignore[reportGeneralTypeIssues] 1gabhijkcdlmnoefpqr

497 else: 

498 

499 def check_gt(v: Any) -> bool: 1gabhijkcdlmnoefpqr

500 return v > gt 1gabhijkcdlmnoefpqr

501 

502 s = _check_func(check_gt, f'> {gt}', s) 1gabhijkcdlmnoefpqr

503 elif isinstance(constraint, annotated_types.Ge): 1gabhijkcdlmnoefpqr

504 ge = constraint.ge 1gabhijkcdlmnoefpqr

505 if s and s['type'] in _ORDERING_SCHEMA_TYPES: 1gabhijkcdlmnoefpqr

506 s = s.copy() 1gabhijkcdlmnoefpqr

507 s['ge'] = ge # pyright: ignore[reportGeneralTypeIssues] 1gabhijkcdlmnoefpqr

508 else: 

509 

510 def check_ge(v: Any) -> bool: 1gabhijkcdlmnoefpqr

511 return v >= ge 1gabhijkcdlmnoefpqr

512 

513 s = _check_func(check_ge, f'>= {ge}', s) 1gabhijkcdlmnoefpqr

514 elif isinstance(constraint, annotated_types.Lt): 1gabhijkcdlmnoefpqr

515 lt = constraint.lt 1gabhijkcdlmnoefpqr

516 if s and s['type'] in _ORDERING_SCHEMA_TYPES: 1gabhijkcdlmnoefpqr

517 s = s.copy() 1gabhijkcdlmnoefpqr

518 s['lt'] = lt # pyright: ignore[reportGeneralTypeIssues] 1gabhijkcdlmnoefpqr

519 else: 

520 

521 def check_lt(v: Any) -> bool: 1gabhijkcdlmnoefpqr

522 return v < lt 1gabhijkcdlmnoefpqr

523 

524 s = _check_func(check_lt, f'< {lt}', s) 1gabhijkcdlmnoefpqr

525 elif isinstance(constraint, annotated_types.Le): 1gabhijkcdlmnoefpqr

526 le = constraint.le 1gabhijkcdlmnoefpqr

527 if s and s['type'] in _ORDERING_SCHEMA_TYPES: 1gabhijkcdlmnoefpqr

528 s = s.copy() 1gabhijkcdlmnoefpqr

529 s['le'] = le # pyright: ignore[reportGeneralTypeIssues] 1gabhijkcdlmnoefpqr

530 else: 

531 

532 def check_le(v: Any) -> bool: 1gabhijkcdlmnoefpqr

533 return v <= le 1gabhijkcdlmnoefpqr

534 

535 s = _check_func(check_le, f'<= {le}', s) 1gabhijkcdlmnoefpqr

536 elif isinstance(constraint, annotated_types.Len): 1gabhijkcdlmnoefpqr

537 min_len = constraint.min_length 1gabhijkcdlmnoefpqr

538 max_len = constraint.max_length 1gabhijkcdlmnoefpqr

539 

540 if s and s['type'] in _LENGTH_SCHEMA_TYPES: 1gabhijkcdlmnoefpqr

541 s = s.copy() 1gabhijkcdlmnoefpqr

542 if min_len != 0: 1gabhijkcdlmnoefpqr

543 s['min_length'] = min_len # pyright: ignore[reportGeneralTypeIssues] 1gabhijkcdlmnoefpqr

544 if max_len is not None: 1gabhijkcdlmnoefpqr

545 s['max_length'] = max_len # pyright: ignore[reportGeneralTypeIssues] 1gabhijkcdlmnoefpqr

546 else: 

547 

548 def check_len(v: Any) -> bool: 1gabhijkcdlmnoefpqr

549 len_v = len(v) 1gabhijkcdlmnoefpqr

550 if max_len is not None: 1gabhijkcdlmnoefpqr

551 return min_len <= len_v <= max_len 1gabhijkcdlmnoefpqr

552 return min_len <= len_v 1gabhijkcdlmnoefpqr

553 

554 predicate_err = ( 1gabhijkcdlmnoefpqr

555 f'length >= {min_len}' if max_len is None else f'length >= {min_len} and length <= {max_len}' 

556 ) 

557 s = _check_func(check_len, predicate_err, s) 1gabhijkcdlmnoefpqr

558 elif isinstance(constraint, annotated_types.MultipleOf): 1gabhijkcdlmnoefpqr

559 multiple_of = constraint.multiple_of 1gabhijkcdlmnoefpqr

560 if s and s['type'] in {'int', 'float', 'decimal'}: 1gabhijkcdlmnoefpqr

561 s = s.copy() 1gabhijkcdlmnoefpqr

562 s['multiple_of'] = multiple_of # pyright: ignore[reportGeneralTypeIssues] 1gabhijkcdlmnoefpqr

563 else: 

564 

565 def check_multiple_of(v: Any) -> bool: 1gabhijkcdlmnoefpqr

566 return v % multiple_of == 0 1gabhijkcdlmnoefpqr

567 

568 s = _check_func(check_multiple_of, f'% {multiple_of} == 0', s) 1gabhijkcdlmnoefpqr

569 elif isinstance(constraint, annotated_types.Timezone): 1gabhijkcdlmnoefpqr

570 tz = constraint.tz 1gabhijkcdlmnoefpqr

571 

572 if tz is ...: 1gabhijkcdlmnoefpqr

573 if s and s['type'] == 'datetime': 1gabhijkcdlmnoefpqr

574 s = s.copy() 1gabhijkcdlmnoefpqr

575 s['tz_constraint'] = 'aware' 1gabhijkcdlmnoefpqr

576 else: 

577 

578 def check_tz_aware(v: object) -> bool: 1gabhijkcdlmnoefpqr

579 assert isinstance(v, datetime.datetime) 1gabhijkcdlmnoefpqr

580 return v.tzinfo is not None 1gabhijkcdlmnoefpqr

581 

582 s = _check_func(check_tz_aware, 'timezone aware', s) 1gabhijkcdlmnoefpqr

583 elif tz is None: 1gabhijkcdlmnoefpqr

584 if s and s['type'] == 'datetime': 1gabhijkcdlmnoefpqr

585 s = s.copy() 1gabhijkcdlmnoefpqr

586 s['tz_constraint'] = 'naive' 1gabhijkcdlmnoefpqr

587 else: 

588 

589 def check_tz_naive(v: object) -> bool: 1gabhijkcdlmnoefpqr

590 assert isinstance(v, datetime.datetime) 1gabhijkcdlmnoefpqr

591 return v.tzinfo is None 1gabhijkcdlmnoefpqr

592 

593 s = _check_func(check_tz_naive, 'timezone naive', s) 1gabhijkcdlmnoefpqr

594 else: 

595 raise NotImplementedError('Constraining to a specific timezone is not yet supported') 

596 elif isinstance(constraint, annotated_types.Interval): 1gabhijkcdlmnoefpqr

597 if constraint.ge is not None: 1gabhijkcdlmnoefpqr

598 s = _apply_constraint(s, annotated_types.Ge(constraint.ge)) 1gabhijkcdlmnoefpqr

599 if constraint.gt is not None: 1gabhijkcdlmnoefpqr

600 s = _apply_constraint(s, annotated_types.Gt(constraint.gt)) 1gabhijkcdlmnoefpqr

601 if constraint.le is not None: 1gabhijkcdlmnoefpqr

602 s = _apply_constraint(s, annotated_types.Le(constraint.le)) 1gabhijkcdlmnoefpqr

603 if constraint.lt is not None: 1gabhijkcdlmnoefpqr

604 s = _apply_constraint(s, annotated_types.Lt(constraint.lt)) 1gabhijkcdlmnoefpqr

605 assert s is not None 1gabhijkcdlmnoefpqr

606 elif isinstance(constraint, annotated_types.Predicate): 1gabhijkcdlmnoefpqr

607 func = constraint.func 1gabhijkcdlmnoefpqr

608 # Same logic as in `_known_annotated_metadata.apply_known_metadata()`: 

609 predicate_name = f'{func.__qualname__!r} ' if hasattr(func, '__qualname__') else '' 1gabhijkcdlmnoefpqr

610 

611 def predicate_func(v: Any) -> Any: 1gabhijkcdlmnoefpqr

612 if not func(v): 1gabhijkcdlmnoefpqr

613 raise PydanticCustomError( 1gabhijkcdlmnoefpqr

614 'predicate_failed', 

615 f'Predicate {predicate_name}failed', # pyright: ignore[reportArgumentType] 

616 ) 

617 return v 1gabhijkcdlmnoefpqr

618 

619 if s is None: 619 ↛ 620line 619 didn't jump to line 620 because the condition on line 619 was never true1gabhijkcdlmnoefpqr

620 s = cs.no_info_plain_validator_function(predicate_func) 

621 else: 

622 s = cs.no_info_after_validator_function(predicate_func, s) 1gabhijkcdlmnoefpqr

623 elif isinstance(constraint, _NotEq): 1gabhijkcdlmnoefpqr

624 value = constraint.value 1gabhijkcdlmnoefpqr

625 

626 def check_not_eq(v: Any) -> bool: 1gabhijkcdlmnoefpqr

627 return operator.__ne__(v, value) 1gabhijkcdlmnoefpqr

628 

629 s = _check_func(check_not_eq, f'!= {value}', s) 1gabhijkcdlmnoefpqr

630 elif isinstance(constraint, _Eq): 1gabhijkcdlmnoefpqr

631 value = constraint.value 1gabhijkcdlmnoefpqr

632 

633 def check_eq(v: Any) -> bool: 1gabhijkcdlmnoefpqr

634 return operator.__eq__(v, value) 1gabhijkcdlmnoefpqr

635 

636 s = _check_func(check_eq, f'== {value}', s) 1gabhijkcdlmnoefpqr

637 elif isinstance(constraint, _In): 1gabhijkcdlmnoefpqr

638 values = constraint.values 1gabhijkcdlmnoefpqr

639 

640 def check_in(v: Any) -> bool: 1gabhijkcdlmnoefpqr

641 return operator.__contains__(values, v) 1gabhijkcdlmnoefpqr

642 

643 s = _check_func(check_in, f'in {values}', s) 1gabhijkcdlmnoefpqr

644 elif isinstance(constraint, _NotIn): 1gabhijkcdlmnoefpqr

645 values = constraint.values 1gabhijkcdlmnoefpqr

646 

647 def check_not_in(v: Any) -> bool: 1gabhijkcdlmnoefpqr

648 return operator.__not__(operator.__contains__(values, v)) 1gabhijkcdlmnoefpqr

649 

650 s = _check_func(check_not_in, f'not in {values}', s) 1gabhijkcdlmnoefpqr

651 else: 

652 assert isinstance(constraint, Pattern) 1gabhijkcdlmnoefpqr

653 if s and s['type'] == 'str': 653 ↛ 658line 653 didn't jump to line 658 because the condition on line 653 was always true1gabhijkcdlmnoefpqr

654 s = s.copy() 1gabhijkcdlmnoefpqr

655 s['pattern'] = constraint 1gabhijkcdlmnoefpqr

656 else: 

657 

658 def check_pattern(v: object) -> bool: 

659 assert isinstance(v, str) 

660 return constraint.match(v) is not None 

661 

662 s = _check_func(check_pattern, f'~ {constraint.pattern}', s) 

663 return s 1gabhijkcdlmnoefpqr

664 

665 

666class _SupportsRange(annotated_types.SupportsLe, annotated_types.SupportsGe, Protocol): 1gabhijkcdlmnoefpqr

667 pass 1gabhijkcdlmnoefpqr

668 

669 

670class _SupportsLen(Protocol): 1gabhijkcdlmnoefpqr

671 def __len__(self) -> int: ... 1gabhijkcdlmnoefpqr

672 

673 

674_NewOutGt = TypeVar('_NewOutGt', bound=annotated_types.SupportsGt) 1gabhijkcdlmnoefpqr

675_NewOutGe = TypeVar('_NewOutGe', bound=annotated_types.SupportsGe) 1gabhijkcdlmnoefpqr

676_NewOutLt = TypeVar('_NewOutLt', bound=annotated_types.SupportsLt) 1gabhijkcdlmnoefpqr

677_NewOutLe = TypeVar('_NewOutLe', bound=annotated_types.SupportsLe) 1gabhijkcdlmnoefpqr

678_NewOutLen = TypeVar('_NewOutLen', bound=_SupportsLen) 1gabhijkcdlmnoefpqr

679_NewOutDiv = TypeVar('_NewOutDiv', bound=annotated_types.SupportsDiv) 1gabhijkcdlmnoefpqr

680_NewOutMod = TypeVar('_NewOutMod', bound=annotated_types.SupportsMod) 1gabhijkcdlmnoefpqr

681_NewOutDatetime = TypeVar('_NewOutDatetime', bound=datetime.datetime) 1gabhijkcdlmnoefpqr

682_NewOutInterval = TypeVar('_NewOutInterval', bound=_SupportsRange) 1gabhijkcdlmnoefpqr

683_OtherIn = TypeVar('_OtherIn') 1gabhijkcdlmnoefpqr

684_OtherOut = TypeVar('_OtherOut') 1gabhijkcdlmnoefpqr