validators.py 21 KB

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