validators.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768
  1. import math
  2. import re
  3. from collections import OrderedDict, deque
  4. from collections.abc import Hashable as CollectionsHashable
  5. from datetime import date, datetime, time, timedelta
  6. from decimal import Decimal, DecimalException
  7. from enum import Enum, IntEnum
  8. from ipaddress import IPv4Address, IPv4Interface, IPv4Network, IPv6Address, IPv6Interface, IPv6Network
  9. from pathlib import Path
  10. from typing import (
  11. TYPE_CHECKING,
  12. Any,
  13. Callable,
  14. Deque,
  15. Dict,
  16. ForwardRef,
  17. FrozenSet,
  18. Generator,
  19. Hashable,
  20. List,
  21. NamedTuple,
  22. Pattern,
  23. Set,
  24. Tuple,
  25. Type,
  26. TypeVar,
  27. Union,
  28. )
  29. from uuid import UUID
  30. from warnings import warn
  31. from pydantic.v1 import errors
  32. from pydantic.v1.datetime_parse import parse_date, parse_datetime, parse_duration, parse_time
  33. from pydantic.v1.typing import (
  34. AnyCallable,
  35. all_literal_values,
  36. display_as_type,
  37. get_class,
  38. is_callable_type,
  39. is_literal_type,
  40. is_namedtuple,
  41. is_none_type,
  42. is_typeddict,
  43. )
  44. from pydantic.v1.utils import almost_equal_floats, lenient_issubclass, sequence_like
  45. if TYPE_CHECKING:
  46. from typing_extensions import Literal, TypedDict
  47. from pydantic.v1.config import BaseConfig
  48. from pydantic.v1.fields import ModelField
  49. from pydantic.v1.types import ConstrainedDecimal, ConstrainedFloat, ConstrainedInt
  50. ConstrainedNumber = Union[ConstrainedDecimal, ConstrainedFloat, ConstrainedInt]
  51. AnyOrderedDict = OrderedDict[Any, Any]
  52. Number = Union[int, float, Decimal]
  53. StrBytes = Union[str, bytes]
  54. def str_validator(v: Any) -> Union[str]:
  55. if isinstance(v, str):
  56. if isinstance(v, Enum):
  57. return v.value
  58. else:
  59. return v
  60. elif isinstance(v, (float, int, Decimal)):
  61. # is there anything else we want to add here? If you think so, create an issue.
  62. return str(v)
  63. elif isinstance(v, (bytes, bytearray)):
  64. return v.decode()
  65. else:
  66. raise errors.StrError()
  67. def strict_str_validator(v: Any) -> Union[str]:
  68. if isinstance(v, str) and not isinstance(v, Enum):
  69. return v
  70. raise errors.StrError()
  71. def bytes_validator(v: Any) -> Union[bytes]:
  72. if isinstance(v, bytes):
  73. return v
  74. elif isinstance(v, bytearray):
  75. return bytes(v)
  76. elif isinstance(v, str):
  77. return v.encode()
  78. elif isinstance(v, (float, int, Decimal)):
  79. return str(v).encode()
  80. else:
  81. raise errors.BytesError()
  82. def strict_bytes_validator(v: Any) -> Union[bytes]:
  83. if isinstance(v, bytes):
  84. return v
  85. elif isinstance(v, bytearray):
  86. return bytes(v)
  87. else:
  88. raise errors.BytesError()
  89. BOOL_FALSE = {0, '0', 'off', 'f', 'false', 'n', 'no'}
  90. BOOL_TRUE = {1, '1', 'on', 't', 'true', 'y', 'yes'}
  91. def bool_validator(v: Any) -> bool:
  92. if v is True or v is False:
  93. return v
  94. if isinstance(v, bytes):
  95. v = v.decode()
  96. if isinstance(v, str):
  97. v = v.lower()
  98. try:
  99. if v in BOOL_TRUE:
  100. return True
  101. if v in BOOL_FALSE:
  102. return False
  103. except TypeError:
  104. raise errors.BoolError()
  105. raise errors.BoolError()
  106. # matches the default limit cpython, see https://github.com/python/cpython/pull/96500
  107. max_str_int = 4_300
  108. def int_validator(v: Any) -> int:
  109. if isinstance(v, int) and not (v is True or v is False):
  110. return v
  111. # see https://github.com/pydantic/pydantic/issues/1477 and in turn, https://github.com/python/cpython/issues/95778
  112. # this check should be unnecessary once patch releases are out for 3.7, 3.8, 3.9 and 3.10
  113. # but better to check here until then.
  114. # NOTICE: this does not fully protect user from the DOS risk since the standard library JSON implementation
  115. # (and other std lib modules like xml) use `int()` and are likely called before this, the best workaround is to
  116. # 1. update to the latest patch release of python once released, 2. use a different JSON library like ujson
  117. if isinstance(v, (str, bytes, bytearray)) and len(v) > max_str_int:
  118. raise errors.IntegerError()
  119. try:
  120. return int(v)
  121. except (TypeError, ValueError, OverflowError):
  122. raise errors.IntegerError()
  123. def strict_int_validator(v: Any) -> int:
  124. if isinstance(v, int) and not (v is True or v is False):
  125. return v
  126. raise errors.IntegerError()
  127. def float_validator(v: Any) -> float:
  128. if isinstance(v, float):
  129. return v
  130. try:
  131. return float(v)
  132. except (TypeError, ValueError):
  133. raise errors.FloatError()
  134. def strict_float_validator(v: Any) -> float:
  135. if isinstance(v, float):
  136. return v
  137. raise errors.FloatError()
  138. def float_finite_validator(v: 'Number', field: 'ModelField', config: 'BaseConfig') -> 'Number':
  139. allow_inf_nan = getattr(field.type_, 'allow_inf_nan', None)
  140. if allow_inf_nan is None:
  141. allow_inf_nan = config.allow_inf_nan
  142. if allow_inf_nan is False and (math.isnan(v) or math.isinf(v)):
  143. raise errors.NumberNotFiniteError()
  144. return v
  145. def number_multiple_validator(v: 'Number', field: 'ModelField') -> 'Number':
  146. field_type: ConstrainedNumber = field.type_
  147. if field_type.multiple_of is not None:
  148. mod = float(v) / float(field_type.multiple_of) % 1
  149. if not almost_equal_floats(mod, 0.0) and not almost_equal_floats(mod, 1.0):
  150. raise errors.NumberNotMultipleError(multiple_of=field_type.multiple_of)
  151. return v
  152. def number_size_validator(v: 'Number', field: 'ModelField') -> 'Number':
  153. field_type: ConstrainedNumber = field.type_
  154. if field_type.gt is not None and not v > field_type.gt:
  155. raise errors.NumberNotGtError(limit_value=field_type.gt)
  156. elif field_type.ge is not None and not v >= field_type.ge:
  157. raise errors.NumberNotGeError(limit_value=field_type.ge)
  158. if field_type.lt is not None and not v < field_type.lt:
  159. raise errors.NumberNotLtError(limit_value=field_type.lt)
  160. if field_type.le is not None and not v <= field_type.le:
  161. raise errors.NumberNotLeError(limit_value=field_type.le)
  162. return v
  163. def constant_validator(v: 'Any', field: 'ModelField') -> 'Any':
  164. """Validate ``const`` fields.
  165. The value provided for a ``const`` field must be equal to the default value
  166. of the field. This is to support the keyword of the same name in JSON
  167. Schema.
  168. """
  169. if v != field.default:
  170. raise errors.WrongConstantError(given=v, permitted=[field.default])
  171. return v
  172. def anystr_length_validator(v: 'StrBytes', config: 'BaseConfig') -> 'StrBytes':
  173. v_len = len(v)
  174. min_length = config.min_anystr_length
  175. if v_len < min_length:
  176. raise errors.AnyStrMinLengthError(limit_value=min_length)
  177. max_length = config.max_anystr_length
  178. if max_length is not None and v_len > max_length:
  179. raise errors.AnyStrMaxLengthError(limit_value=max_length)
  180. return v
  181. def anystr_strip_whitespace(v: 'StrBytes') -> 'StrBytes':
  182. return v.strip()
  183. def anystr_upper(v: 'StrBytes') -> 'StrBytes':
  184. return v.upper()
  185. def anystr_lower(v: 'StrBytes') -> 'StrBytes':
  186. return v.lower()
  187. def ordered_dict_validator(v: Any) -> 'AnyOrderedDict':
  188. if isinstance(v, OrderedDict):
  189. return v
  190. try:
  191. return OrderedDict(v)
  192. except (TypeError, ValueError):
  193. raise errors.DictError()
  194. def dict_validator(v: Any) -> Dict[Any, Any]:
  195. if isinstance(v, dict):
  196. return v
  197. try:
  198. return dict(v)
  199. except (TypeError, ValueError):
  200. raise errors.DictError()
  201. def list_validator(v: Any) -> List[Any]:
  202. if isinstance(v, list):
  203. return v
  204. elif sequence_like(v):
  205. return list(v)
  206. else:
  207. raise errors.ListError()
  208. def tuple_validator(v: Any) -> Tuple[Any, ...]:
  209. if isinstance(v, tuple):
  210. return v
  211. elif sequence_like(v):
  212. return tuple(v)
  213. else:
  214. raise errors.TupleError()
  215. def set_validator(v: Any) -> Set[Any]:
  216. if isinstance(v, set):
  217. return v
  218. elif sequence_like(v):
  219. return set(v)
  220. else:
  221. raise errors.SetError()
  222. def frozenset_validator(v: Any) -> FrozenSet[Any]:
  223. if isinstance(v, frozenset):
  224. return v
  225. elif sequence_like(v):
  226. return frozenset(v)
  227. else:
  228. raise errors.FrozenSetError()
  229. def deque_validator(v: Any) -> Deque[Any]:
  230. if isinstance(v, deque):
  231. return v
  232. elif sequence_like(v):
  233. return deque(v)
  234. else:
  235. raise errors.DequeError()
  236. def enum_member_validator(v: Any, field: 'ModelField', config: 'BaseConfig') -> Enum:
  237. try:
  238. enum_v = field.type_(v)
  239. except ValueError:
  240. # field.type_ should be an enum, so will be iterable
  241. raise errors.EnumMemberError(enum_values=list(field.type_))
  242. return enum_v.value if config.use_enum_values else enum_v
  243. def uuid_validator(v: Any, field: 'ModelField') -> UUID:
  244. try:
  245. if isinstance(v, str):
  246. v = UUID(v)
  247. elif isinstance(v, (bytes, bytearray)):
  248. try:
  249. v = UUID(v.decode())
  250. except ValueError:
  251. # 16 bytes in big-endian order as the bytes argument fail
  252. # the above check
  253. v = UUID(bytes=v)
  254. except ValueError:
  255. raise errors.UUIDError()
  256. if not isinstance(v, UUID):
  257. raise errors.UUIDError()
  258. required_version = getattr(field.type_, '_required_version', None)
  259. if required_version and v.version != required_version:
  260. raise errors.UUIDVersionError(required_version=required_version)
  261. return v
  262. def decimal_validator(v: Any) -> Decimal:
  263. if isinstance(v, Decimal):
  264. return v
  265. elif isinstance(v, (bytes, bytearray)):
  266. v = v.decode()
  267. v = str(v).strip()
  268. try:
  269. v = Decimal(v)
  270. except DecimalException:
  271. raise errors.DecimalError()
  272. if not v.is_finite():
  273. raise errors.DecimalIsNotFiniteError()
  274. return v
  275. def hashable_validator(v: Any) -> Hashable:
  276. if isinstance(v, Hashable):
  277. return v
  278. raise errors.HashableError()
  279. def ip_v4_address_validator(v: Any) -> IPv4Address:
  280. if isinstance(v, IPv4Address):
  281. return v
  282. try:
  283. return IPv4Address(v)
  284. except ValueError:
  285. raise errors.IPv4AddressError()
  286. def ip_v6_address_validator(v: Any) -> IPv6Address:
  287. if isinstance(v, IPv6Address):
  288. return v
  289. try:
  290. return IPv6Address(v)
  291. except ValueError:
  292. raise errors.IPv6AddressError()
  293. def ip_v4_network_validator(v: Any) -> IPv4Network:
  294. """
  295. Assume IPv4Network initialised with a default ``strict`` argument
  296. See more:
  297. https://docs.python.org/library/ipaddress.html#ipaddress.IPv4Network
  298. """
  299. if isinstance(v, IPv4Network):
  300. return v
  301. try:
  302. return IPv4Network(v)
  303. except ValueError:
  304. raise errors.IPv4NetworkError()
  305. def ip_v6_network_validator(v: Any) -> IPv6Network:
  306. """
  307. Assume IPv6Network initialised with a default ``strict`` argument
  308. See more:
  309. https://docs.python.org/library/ipaddress.html#ipaddress.IPv6Network
  310. """
  311. if isinstance(v, IPv6Network):
  312. return v
  313. try:
  314. return IPv6Network(v)
  315. except ValueError:
  316. raise errors.IPv6NetworkError()
  317. def ip_v4_interface_validator(v: Any) -> IPv4Interface:
  318. if isinstance(v, IPv4Interface):
  319. return v
  320. try:
  321. return IPv4Interface(v)
  322. except ValueError:
  323. raise errors.IPv4InterfaceError()
  324. def ip_v6_interface_validator(v: Any) -> IPv6Interface:
  325. if isinstance(v, IPv6Interface):
  326. return v
  327. try:
  328. return IPv6Interface(v)
  329. except ValueError:
  330. raise errors.IPv6InterfaceError()
  331. def path_validator(v: Any) -> Path:
  332. if isinstance(v, Path):
  333. return v
  334. try:
  335. return Path(v)
  336. except TypeError:
  337. raise errors.PathError()
  338. def path_exists_validator(v: Any) -> Path:
  339. if not v.exists():
  340. raise errors.PathNotExistsError(path=v)
  341. return v
  342. def callable_validator(v: Any) -> AnyCallable:
  343. """
  344. Perform a simple check if the value is callable.
  345. Note: complete matching of argument type hints and return types is not performed
  346. """
  347. if callable(v):
  348. return v
  349. raise errors.CallableError(value=v)
  350. def enum_validator(v: Any) -> Enum:
  351. if isinstance(v, Enum):
  352. return v
  353. raise errors.EnumError(value=v)
  354. def int_enum_validator(v: Any) -> IntEnum:
  355. if isinstance(v, IntEnum):
  356. return v
  357. raise errors.IntEnumError(value=v)
  358. def make_literal_validator(type_: Any) -> Callable[[Any], Any]:
  359. permitted_choices = all_literal_values(type_)
  360. # To have a O(1) complexity and still return one of the values set inside the `Literal`,
  361. # we create a dict with the set values (a set causes some problems with the way intersection works).
  362. # In some cases the set value and checked value can indeed be different (see `test_literal_validator_str_enum`)
  363. allowed_choices = {v: v for v in permitted_choices}
  364. def literal_validator(v: Any) -> Any:
  365. try:
  366. return allowed_choices[v]
  367. except (KeyError, TypeError):
  368. raise errors.WrongConstantError(given=v, permitted=permitted_choices)
  369. return literal_validator
  370. def constr_length_validator(v: 'StrBytes', field: 'ModelField', config: 'BaseConfig') -> 'StrBytes':
  371. v_len = len(v)
  372. min_length = field.type_.min_length if field.type_.min_length is not None else config.min_anystr_length
  373. if v_len < min_length:
  374. raise errors.AnyStrMinLengthError(limit_value=min_length)
  375. max_length = field.type_.max_length if field.type_.max_length is not None else config.max_anystr_length
  376. if max_length is not None and v_len > max_length:
  377. raise errors.AnyStrMaxLengthError(limit_value=max_length)
  378. return v
  379. def constr_strip_whitespace(v: 'StrBytes', field: 'ModelField', config: 'BaseConfig') -> 'StrBytes':
  380. strip_whitespace = field.type_.strip_whitespace or config.anystr_strip_whitespace
  381. if strip_whitespace:
  382. v = v.strip()
  383. return v
  384. def constr_upper(v: 'StrBytes', field: 'ModelField', config: 'BaseConfig') -> 'StrBytes':
  385. upper = field.type_.to_upper or config.anystr_upper
  386. if upper:
  387. v = v.upper()
  388. return v
  389. def constr_lower(v: 'StrBytes', field: 'ModelField', config: 'BaseConfig') -> 'StrBytes':
  390. lower = field.type_.to_lower or config.anystr_lower
  391. if lower:
  392. v = v.lower()
  393. return v
  394. def validate_json(v: Any, config: 'BaseConfig') -> Any:
  395. if v is None:
  396. # pass None through to other validators
  397. return v
  398. try:
  399. return config.json_loads(v) # type: ignore
  400. except ValueError:
  401. raise errors.JsonError()
  402. except TypeError:
  403. raise errors.JsonTypeError()
  404. T = TypeVar('T')
  405. def make_arbitrary_type_validator(type_: Type[T]) -> Callable[[T], T]:
  406. def arbitrary_type_validator(v: Any) -> T:
  407. if isinstance(v, type_):
  408. return v
  409. raise errors.ArbitraryTypeError(expected_arbitrary_type=type_)
  410. return arbitrary_type_validator
  411. def make_class_validator(type_: Type[T]) -> Callable[[Any], Type[T]]:
  412. def class_validator(v: Any) -> Type[T]:
  413. if lenient_issubclass(v, type_):
  414. return v
  415. raise errors.SubclassError(expected_class=type_)
  416. return class_validator
  417. def any_class_validator(v: Any) -> Type[T]:
  418. if isinstance(v, type):
  419. return v
  420. raise errors.ClassError()
  421. def none_validator(v: Any) -> 'Literal[None]':
  422. if v is None:
  423. return v
  424. raise errors.NotNoneError()
  425. def pattern_validator(v: Any) -> Pattern[str]:
  426. if isinstance(v, Pattern):
  427. return v
  428. str_value = str_validator(v)
  429. try:
  430. return re.compile(str_value)
  431. except re.error:
  432. raise errors.PatternError()
  433. NamedTupleT = TypeVar('NamedTupleT', bound=NamedTuple)
  434. def make_namedtuple_validator(
  435. namedtuple_cls: Type[NamedTupleT], config: Type['BaseConfig']
  436. ) -> Callable[[Tuple[Any, ...]], NamedTupleT]:
  437. from pydantic.v1.annotated_types import create_model_from_namedtuple
  438. NamedTupleModel = create_model_from_namedtuple(
  439. namedtuple_cls,
  440. __config__=config,
  441. __module__=namedtuple_cls.__module__,
  442. )
  443. namedtuple_cls.__pydantic_model__ = NamedTupleModel # type: ignore[attr-defined]
  444. def namedtuple_validator(values: Tuple[Any, ...]) -> NamedTupleT:
  445. annotations = NamedTupleModel.__annotations__
  446. if len(values) > len(annotations):
  447. raise errors.ListMaxLengthError(limit_value=len(annotations))
  448. dict_values: Dict[str, Any] = dict(zip(annotations, values))
  449. validated_dict_values: Dict[str, Any] = dict(NamedTupleModel(**dict_values))
  450. return namedtuple_cls(**validated_dict_values)
  451. return namedtuple_validator
  452. def make_typeddict_validator(
  453. typeddict_cls: Type['TypedDict'], config: Type['BaseConfig'] # type: ignore[valid-type]
  454. ) -> Callable[[Any], Dict[str, Any]]:
  455. from pydantic.v1.annotated_types import create_model_from_typeddict
  456. TypedDictModel = create_model_from_typeddict(
  457. typeddict_cls,
  458. __config__=config,
  459. __module__=typeddict_cls.__module__,
  460. )
  461. typeddict_cls.__pydantic_model__ = TypedDictModel # type: ignore[attr-defined]
  462. def typeddict_validator(values: 'TypedDict') -> Dict[str, Any]: # type: ignore[valid-type]
  463. return TypedDictModel.parse_obj(values).dict(exclude_unset=True)
  464. return typeddict_validator
  465. class IfConfig:
  466. def __init__(self, validator: AnyCallable, *config_attr_names: str, ignored_value: Any = False) -> None:
  467. self.validator = validator
  468. self.config_attr_names = config_attr_names
  469. self.ignored_value = ignored_value
  470. def check(self, config: Type['BaseConfig']) -> bool:
  471. return any(getattr(config, name) not in {None, self.ignored_value} for name in self.config_attr_names)
  472. # order is important here, for example: bool is a subclass of int so has to come first, datetime before date same,
  473. # IPv4Interface before IPv4Address, etc
  474. _VALIDATORS: List[Tuple[Type[Any], List[Any]]] = [
  475. (IntEnum, [int_validator, enum_member_validator]),
  476. (Enum, [enum_member_validator]),
  477. (
  478. str,
  479. [
  480. str_validator,
  481. IfConfig(anystr_strip_whitespace, 'anystr_strip_whitespace'),
  482. IfConfig(anystr_upper, 'anystr_upper'),
  483. IfConfig(anystr_lower, 'anystr_lower'),
  484. IfConfig(anystr_length_validator, 'min_anystr_length', 'max_anystr_length'),
  485. ],
  486. ),
  487. (
  488. bytes,
  489. [
  490. bytes_validator,
  491. IfConfig(anystr_strip_whitespace, 'anystr_strip_whitespace'),
  492. IfConfig(anystr_upper, 'anystr_upper'),
  493. IfConfig(anystr_lower, 'anystr_lower'),
  494. IfConfig(anystr_length_validator, 'min_anystr_length', 'max_anystr_length'),
  495. ],
  496. ),
  497. (bool, [bool_validator]),
  498. (int, [int_validator]),
  499. (float, [float_validator, IfConfig(float_finite_validator, 'allow_inf_nan', ignored_value=True)]),
  500. (Path, [path_validator]),
  501. (datetime, [parse_datetime]),
  502. (date, [parse_date]),
  503. (time, [parse_time]),
  504. (timedelta, [parse_duration]),
  505. (OrderedDict, [ordered_dict_validator]),
  506. (dict, [dict_validator]),
  507. (list, [list_validator]),
  508. (tuple, [tuple_validator]),
  509. (set, [set_validator]),
  510. (frozenset, [frozenset_validator]),
  511. (deque, [deque_validator]),
  512. (UUID, [uuid_validator]),
  513. (Decimal, [decimal_validator]),
  514. (IPv4Interface, [ip_v4_interface_validator]),
  515. (IPv6Interface, [ip_v6_interface_validator]),
  516. (IPv4Address, [ip_v4_address_validator]),
  517. (IPv6Address, [ip_v6_address_validator]),
  518. (IPv4Network, [ip_v4_network_validator]),
  519. (IPv6Network, [ip_v6_network_validator]),
  520. ]
  521. def find_validators( # noqa: C901 (ignore complexity)
  522. type_: Type[Any], config: Type['BaseConfig']
  523. ) -> Generator[AnyCallable, None, None]:
  524. from pydantic.v1.dataclasses import is_builtin_dataclass, make_dataclass_validator
  525. if type_ is Any or type_ is object:
  526. return
  527. type_type = type_.__class__
  528. if type_type == ForwardRef or type_type == TypeVar:
  529. return
  530. if is_none_type(type_):
  531. yield none_validator
  532. return
  533. if type_ is Pattern or type_ is re.Pattern:
  534. yield pattern_validator
  535. return
  536. if type_ is Hashable or type_ is CollectionsHashable:
  537. yield hashable_validator
  538. return
  539. if is_callable_type(type_):
  540. yield callable_validator
  541. return
  542. if is_literal_type(type_):
  543. yield make_literal_validator(type_)
  544. return
  545. if is_builtin_dataclass(type_):
  546. yield from make_dataclass_validator(type_, config)
  547. return
  548. if type_ is Enum:
  549. yield enum_validator
  550. return
  551. if type_ is IntEnum:
  552. yield int_enum_validator
  553. return
  554. if is_namedtuple(type_):
  555. yield tuple_validator
  556. yield make_namedtuple_validator(type_, config)
  557. return
  558. if is_typeddict(type_):
  559. yield make_typeddict_validator(type_, config)
  560. return
  561. class_ = get_class(type_)
  562. if class_ is not None:
  563. if class_ is not Any and isinstance(class_, type):
  564. yield make_class_validator(class_)
  565. else:
  566. yield any_class_validator
  567. return
  568. for val_type, validators in _VALIDATORS:
  569. try:
  570. if issubclass(type_, val_type):
  571. for v in validators:
  572. if isinstance(v, IfConfig):
  573. if v.check(config):
  574. yield v.validator
  575. else:
  576. yield v
  577. return
  578. except TypeError:
  579. raise RuntimeError(f'error checking inheritance of {type_!r} (type: {display_as_type(type_)})')
  580. if config.arbitrary_types_allowed:
  581. yield make_arbitrary_type_validator(type_)
  582. else:
  583. if hasattr(type_, '__pydantic_core_schema__'):
  584. warn(f'Mixing V1 and V2 models is not supported. `{type_.__name__}` is a V2 model.', UserWarning)
  585. raise RuntimeError(f'no validator found for {type_}, see `arbitrary_types_allowed` in Config')