pboot-validator 1.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (112) hide show
  1. pboot_validator/__init__.py +461 -0
  2. pboot_validator/_internal/__init__.py +0 -0
  3. pboot_validator/_internal/_config.py +408 -0
  4. pboot_validator/_internal/_contextlib.py +84 -0
  5. pboot_validator/_internal/_core_metadata.py +97 -0
  6. pboot_validator/_internal/_core_utils.py +156 -0
  7. pboot_validator/_internal/_dataclasses.py +327 -0
  8. pboot_validator/_internal/_decorators.py +906 -0
  9. pboot_validator/_internal/_decorators_v1.py +174 -0
  10. pboot_validator/_internal/_discriminated_union.py +510 -0
  11. pboot_validator/_internal/_docs_extraction.py +128 -0
  12. pboot_validator/_internal/_fields.py +910 -0
  13. pboot_validator/_internal/_forward_ref.py +23 -0
  14. pboot_validator/_internal/_generate_schema.py +3053 -0
  15. pboot_validator/_internal/_generics.py +572 -0
  16. pboot_validator/_internal/_git.py +27 -0
  17. pboot_validator/_internal/_import_utils.py +20 -0
  18. pboot_validator/_internal/_known_annotated_metadata.py +412 -0
  19. pboot_validator/_internal/_mock_val_ser.py +241 -0
  20. pboot_validator/_internal/_model_construction.py +833 -0
  21. pboot_validator/_internal/_namespace_utils.py +300 -0
  22. pboot_validator/_internal/_repr.py +129 -0
  23. pboot_validator/_internal/_schema_gather.py +49 -0
  24. pboot_validator/_internal/_schema_generation_shared.py +126 -0
  25. pboot_validator/_internal/_serializers.py +59 -0
  26. pboot_validator/_internal/_signature.py +193 -0
  27. pboot_validator/_internal/_type_refs.py +128 -0
  28. pboot_validator/_internal/_typing_extra.py +506 -0
  29. pboot_validator/_internal/_utils.py +433 -0
  30. pboot_validator/_internal/_validate_call.py +141 -0
  31. pboot_validator/_internal/_validators.py +541 -0
  32. pboot_validator/_migration.py +317 -0
  33. pboot_validator/alias_generators.py +62 -0
  34. pboot_validator/aliases.py +136 -0
  35. pboot_validator/annotated_handlers.py +123 -0
  36. pboot_validator/class_validators.py +5 -0
  37. pboot_validator/color.py +605 -0
  38. pboot_validator/config.py +1295 -0
  39. pboot_validator/dataclasses.py +385 -0
  40. pboot_validator/datetime_parse.py +5 -0
  41. pboot_validator/decorator.py +5 -0
  42. pboot_validator/deprecated/__init__.py +0 -0
  43. pboot_validator/deprecated/class_validators.py +257 -0
  44. pboot_validator/deprecated/config.py +72 -0
  45. pboot_validator/deprecated/copy_internals.py +224 -0
  46. pboot_validator/deprecated/decorator.py +286 -0
  47. pboot_validator/deprecated/json.py +142 -0
  48. pboot_validator/deprecated/parse.py +81 -0
  49. pboot_validator/deprecated/tools.py +104 -0
  50. pboot_validator/env_settings.py +5 -0
  51. pboot_validator/error_wrappers.py +5 -0
  52. pboot_validator/errors.py +185 -0
  53. pboot_validator/experimental/__init__.py +1 -0
  54. pboot_validator/experimental/arguments_schema.py +44 -0
  55. pboot_validator/experimental/missing_sentinel.py +29 -0
  56. pboot_validator/experimental/pipeline.py +684 -0
  57. pboot_validator/fields.py +2065 -0
  58. pboot_validator/functional_serializers.py +461 -0
  59. pboot_validator/functional_validators.py +920 -0
  60. pboot_validator/generics.py +5 -0
  61. pboot_validator/json.py +5 -0
  62. pboot_validator/json_schema.py +3283 -0
  63. pboot_validator/main.py +1947 -0
  64. pboot_validator/mypy.py +1469 -0
  65. pboot_validator/networks.py +1417 -0
  66. pboot_validator/parse.py +5 -0
  67. pboot_validator/plugin/__init__.py +190 -0
  68. pboot_validator/plugin/_loader.py +56 -0
  69. pboot_validator/plugin/_schema_validator.py +152 -0
  70. pboot_validator/py.typed +0 -0
  71. pboot_validator/root_model.py +189 -0
  72. pboot_validator/schema.py +5 -0
  73. pboot_validator/tools.py +5 -0
  74. pboot_validator/type_adapter.py +780 -0
  75. pboot_validator/types.py +3405 -0
  76. pboot_validator/typing.py +5 -0
  77. pboot_validator/utils.py +5 -0
  78. pboot_validator/v1/__init__.py +131 -0
  79. pboot_validator/v1/_hypothesis_plugin.py +391 -0
  80. pboot_validator/v1/annotated_types.py +72 -0
  81. pboot_validator/v1/class_validators.py +361 -0
  82. pboot_validator/v1/color.py +494 -0
  83. pboot_validator/v1/config.py +191 -0
  84. pboot_validator/v1/dataclasses.py +503 -0
  85. pboot_validator/v1/datetime_parse.py +248 -0
  86. pboot_validator/v1/decorator.py +264 -0
  87. pboot_validator/v1/env_settings.py +350 -0
  88. pboot_validator/v1/error_wrappers.py +161 -0
  89. pboot_validator/v1/errors.py +646 -0
  90. pboot_validator/v1/fields.py +1253 -0
  91. pboot_validator/v1/generics.py +400 -0
  92. pboot_validator/v1/json.py +112 -0
  93. pboot_validator/v1/main.py +1130 -0
  94. pboot_validator/v1/mypy.py +950 -0
  95. pboot_validator/v1/networks.py +747 -0
  96. pboot_validator/v1/parse.py +66 -0
  97. pboot_validator/v1/py.typed +0 -0
  98. pboot_validator/v1/schema.py +1163 -0
  99. pboot_validator/v1/tools.py +92 -0
  100. pboot_validator/v1/types.py +1213 -0
  101. pboot_validator/v1/typing.py +627 -0
  102. pboot_validator/v1/utils.py +807 -0
  103. pboot_validator/v1/validators.py +768 -0
  104. pboot_validator/v1/version.py +38 -0
  105. pboot_validator/validate_call_decorator.py +121 -0
  106. pboot_validator/validators.py +5 -0
  107. pboot_validator/version.py +113 -0
  108. pboot_validator/warnings.py +130 -0
  109. pboot_validator-1.0.0.dist-info/METADATA +93 -0
  110. pboot_validator-1.0.0.dist-info/RECORD +112 -0
  111. pboot_validator-1.0.0.dist-info/WHEEL +4 -0
  112. pboot_validator-1.0.0.dist-info/licenses/LICENSE +21 -0
@@ -0,0 +1,627 @@
1
+ import functools
2
+ import operator
3
+ import sys
4
+ import typing
5
+ from collections.abc import Callable
6
+ from os import PathLike
7
+ from typing import ( # type: ignore
8
+ TYPE_CHECKING,
9
+ AbstractSet,
10
+ Any,
11
+ Callable as TypingCallable,
12
+ ClassVar,
13
+ Dict,
14
+ ForwardRef,
15
+ Generator,
16
+ Iterable,
17
+ List,
18
+ Mapping,
19
+ NewType,
20
+ Optional,
21
+ Sequence,
22
+ Set,
23
+ Tuple,
24
+ Type,
25
+ TypeVar,
26
+ Union,
27
+ _eval_type,
28
+ cast,
29
+ get_type_hints,
30
+ )
31
+
32
+ from typing_extensions import (
33
+ Annotated,
34
+ Final,
35
+ Literal,
36
+ NotRequired as TypedDictNotRequired,
37
+ Required as TypedDictRequired,
38
+ )
39
+
40
+ try:
41
+ from typing import _TypingBase as typing_base # type: ignore
42
+ except ImportError:
43
+ from typing import _Final as typing_base # type: ignore
44
+
45
+ try:
46
+ from typing import GenericAlias as TypingGenericAlias # type: ignore
47
+ except ImportError:
48
+ # python < 3.9 does not have GenericAlias (list[int], tuple[str, ...] and so on)
49
+ TypingGenericAlias = ()
50
+
51
+ try:
52
+ from types import UnionType as TypesUnionType # type: ignore
53
+ except ImportError:
54
+ # python < 3.10 does not have UnionType (str | int, byte | bool and so on)
55
+ TypesUnionType = ()
56
+
57
+
58
+ if sys.version_info < (3, 9):
59
+
60
+ def evaluate_forwardref(type_: ForwardRef, globalns: Any, localns: Any) -> Any:
61
+ return type_._evaluate(globalns, localns)
62
+
63
+ elif sys.version_info < (3, 12, 4):
64
+
65
+ def evaluate_forwardref(type_: ForwardRef, globalns: Any, localns: Any) -> Any:
66
+ # Even though it is the right signature for python 3.9, mypy complains with
67
+ # `error: Too many arguments for "_evaluate" of "ForwardRef"` hence the cast...
68
+ # Python 3.13/3.12.4+ made `recursive_guard` a kwarg, so name it explicitly to avoid:
69
+ # TypeError: ForwardRef._evaluate() missing 1 required keyword-only argument: 'recursive_guard'
70
+ return cast(Any, type_)._evaluate(globalns, localns, recursive_guard=set())
71
+
72
+ elif sys.version_info < (3, 14):
73
+
74
+ def evaluate_forwardref(type_: ForwardRef, globalns: Any, localns: Any) -> Any:
75
+ # Pydantic 1.x will not support PEP 695 syntax, but provide `type_params` to avoid
76
+ # warnings:
77
+ return cast(Any, type_)._evaluate(globalns, localns, type_params=(), recursive_guard=set())
78
+
79
+ else:
80
+
81
+ def evaluate_forwardref(type_: ForwardRef, globalns: Any, localns: Any) -> Any:
82
+ # Pydantic 1.x will not support PEP 695 syntax, but provide `type_params` to avoid
83
+ # warnings:
84
+ return typing.evaluate_forward_ref(
85
+ type_,
86
+ globals=globalns,
87
+ locals=localns,
88
+ type_params=(),
89
+ _recursive_guard=set(),
90
+ )
91
+
92
+
93
+ if sys.version_info < (3, 9):
94
+ # Ensure we always get all the whole `Annotated` hint, not just the annotated type.
95
+ # For 3.7 to 3.8, `get_type_hints` doesn't recognize `typing_extensions.Annotated`,
96
+ # so it already returns the full annotation
97
+ get_all_type_hints = get_type_hints
98
+
99
+ else:
100
+
101
+ def get_all_type_hints(obj: Any, globalns: Any = None, localns: Any = None) -> Any:
102
+ return get_type_hints(obj, globalns, localns, include_extras=True)
103
+
104
+
105
+ _T = TypeVar('_T')
106
+
107
+ AnyCallable = TypingCallable[..., Any]
108
+ NoArgAnyCallable = TypingCallable[[], Any]
109
+
110
+ # workaround for https://github.com/python/mypy/issues/9496
111
+ AnyArgTCallable = TypingCallable[..., _T]
112
+
113
+
114
+ # Annotated[...] is implemented by returning an instance of one of these classes, depending on
115
+ # python/typing_extensions version.
116
+ AnnotatedTypeNames = {'AnnotatedMeta', '_AnnotatedAlias'}
117
+
118
+
119
+ LITERAL_TYPES: Set[Any] = {Literal}
120
+ if hasattr(typing, 'Literal'):
121
+ LITERAL_TYPES.add(typing.Literal)
122
+
123
+
124
+ if sys.version_info < (3, 8):
125
+
126
+ def get_origin(t: Type[Any]) -> Optional[Type[Any]]:
127
+ if type(t).__name__ in AnnotatedTypeNames:
128
+ # weirdly this is a runtime requirement, as well as for mypy
129
+ return cast(Type[Any], Annotated)
130
+ return getattr(t, '__origin__', None)
131
+
132
+ else:
133
+ from typing import get_origin as _typing_get_origin
134
+
135
+ def get_origin(tp: Type[Any]) -> Optional[Type[Any]]:
136
+ """
137
+ We can't directly use `typing.get_origin` since we need a fallback to support
138
+ custom generic classes like `ConstrainedList`
139
+ It should be useless once https://github.com/cython/cython/issues/3537 is
140
+ solved and https://github.com/pydantic/pydantic/pull/1753 is merged.
141
+ """
142
+ if type(tp).__name__ in AnnotatedTypeNames:
143
+ return cast(Type[Any], Annotated) # mypy complains about _SpecialForm
144
+ return _typing_get_origin(tp) or getattr(tp, '__origin__', None)
145
+
146
+
147
+ if sys.version_info < (3, 8):
148
+ from typing import _GenericAlias
149
+
150
+ def get_args(t: Type[Any]) -> Tuple[Any, ...]:
151
+ """Compatibility version of get_args for python 3.7.
152
+
153
+ Mostly compatible with the python 3.8 `typing` module version
154
+ and able to handle almost all use cases.
155
+ """
156
+ if type(t).__name__ in AnnotatedTypeNames:
157
+ return t.__args__ + t.__metadata__
158
+ if isinstance(t, _GenericAlias):
159
+ res = t.__args__
160
+ if t.__origin__ is Callable and res and res[0] is not Ellipsis:
161
+ res = (list(res[:-1]), res[-1])
162
+ return res
163
+ return getattr(t, '__args__', ())
164
+
165
+ else:
166
+ from typing import get_args as _typing_get_args
167
+
168
+ def _generic_get_args(tp: Type[Any]) -> Tuple[Any, ...]:
169
+ """
170
+ In python 3.9, `typing.Dict`, `typing.List`, ...
171
+ do have an empty `__args__` by default (instead of the generic ~T for example).
172
+ In order to still support `Dict` for example and consider it as `Dict[Any, Any]`,
173
+ we retrieve the `_nparams` value that tells us how many parameters it needs.
174
+ """
175
+ if hasattr(tp, '_nparams'):
176
+ return (Any,) * tp._nparams
177
+ # Special case for `tuple[()]`, which used to return ((),) with `typing.Tuple`
178
+ # in python 3.10- but now returns () for `tuple` and `Tuple`.
179
+ # This will probably be clarified in pydantic v2
180
+ try:
181
+ if tp == Tuple[()] or sys.version_info >= (3, 9) and tp == tuple[()]: # type: ignore[misc]
182
+ return ((),)
183
+ # there is a TypeError when compiled with cython
184
+ except TypeError: # pragma: no cover
185
+ pass
186
+ return ()
187
+
188
+ def get_args(tp: Type[Any]) -> Tuple[Any, ...]:
189
+ """Get type arguments with all substitutions performed.
190
+
191
+ For unions, basic simplifications used by Union constructor are performed.
192
+ Examples::
193
+ get_args(Dict[str, int]) == (str, int)
194
+ get_args(int) == ()
195
+ get_args(Union[int, Union[T, int], str][int]) == (int, str)
196
+ get_args(Union[int, Tuple[T, int]][str]) == (int, Tuple[str, int])
197
+ get_args(Callable[[], T][int]) == ([], int)
198
+ """
199
+ if type(tp).__name__ in AnnotatedTypeNames:
200
+ return tp.__args__ + tp.__metadata__
201
+ # the fallback is needed for the same reasons as `get_origin` (see above)
202
+ return _typing_get_args(tp) or getattr(tp, '__args__', ()) or _generic_get_args(tp)
203
+
204
+
205
+ if sys.version_info < (3, 9):
206
+
207
+ def convert_generics(tp: Type[Any]) -> Type[Any]:
208
+ """Python 3.9 and older only supports generics from `typing` module.
209
+ They convert strings to ForwardRef automatically.
210
+
211
+ Examples::
212
+ typing.List['Hero'] == typing.List[ForwardRef('Hero')]
213
+ """
214
+ return tp
215
+
216
+ else:
217
+
218
+ def convert_generics(tp: Type[Any]) -> Type[Any]:
219
+ """
220
+ Recursively searches for `str` type hints and replaces them with ForwardRef.
221
+
222
+ Examples::
223
+ convert_generics(list['Hero']) == list[ForwardRef('Hero')]
224
+ convert_generics(dict['Hero', 'Team']) == dict[ForwardRef('Hero'), ForwardRef('Team')]
225
+ convert_generics(typing.Dict['Hero', 'Team']) == typing.Dict[ForwardRef('Hero'), ForwardRef('Team')]
226
+ convert_generics(list[str | 'Hero'] | int) == list[str | ForwardRef('Hero')] | int
227
+ """
228
+ origin = get_origin(tp)
229
+ if not origin or not hasattr(tp, '__args__'):
230
+ return tp
231
+
232
+ args = get_args(tp)
233
+
234
+ # typing.Annotated needs special treatment
235
+ if origin is Annotated:
236
+ return Annotated[(convert_generics(args[0]), *args[1:])] # type: ignore
237
+
238
+ # recursively replace `str` instances inside of `GenericAlias` with `ForwardRef(arg)`
239
+ converted = tuple(
240
+ ForwardRef(arg) if isinstance(arg, str) and isinstance(tp, TypingGenericAlias) else convert_generics(arg)
241
+ for arg in args
242
+ )
243
+
244
+ if converted == args:
245
+ return tp
246
+ elif isinstance(tp, TypingGenericAlias):
247
+ return TypingGenericAlias(origin, converted)
248
+ elif isinstance(tp, TypesUnionType):
249
+ # recreate types.UnionType (PEP604, Python >= 3.10)
250
+ return functools.reduce(operator.or_, converted) # type: ignore
251
+ else:
252
+ try:
253
+ setattr(tp, '__args__', converted)
254
+ except AttributeError:
255
+ pass
256
+ return tp
257
+
258
+
259
+ if sys.version_info < (3, 10):
260
+
261
+ def is_union(tp: Optional[Type[Any]]) -> bool:
262
+ return tp is Union
263
+
264
+ WithArgsTypes = (TypingGenericAlias,)
265
+
266
+ else:
267
+ import types
268
+ import typing
269
+
270
+ def is_union(tp: Optional[Type[Any]]) -> bool:
271
+ return tp is Union or tp is types.UnionType # noqa: E721
272
+
273
+ WithArgsTypes = (typing._GenericAlias, types.GenericAlias, types.UnionType)
274
+
275
+
276
+ StrPath = Union[str, PathLike]
277
+
278
+
279
+ if TYPE_CHECKING:
280
+ from pboot_validator.v1.fields import ModelField
281
+
282
+ TupleGenerator = Generator[Tuple[str, Any], None, None]
283
+ DictStrAny = Dict[str, Any]
284
+ DictAny = Dict[Any, Any]
285
+ SetStr = Set[str]
286
+ ListStr = List[str]
287
+ IntStr = Union[int, str]
288
+ AbstractSetIntStr = AbstractSet[IntStr]
289
+ DictIntStrAny = Dict[IntStr, Any]
290
+ MappingIntStrAny = Mapping[IntStr, Any]
291
+ CallableGenerator = Generator[AnyCallable, None, None]
292
+ ReprArgs = Sequence[Tuple[Optional[str], Any]]
293
+
294
+ MYPY = False
295
+ if MYPY:
296
+ AnyClassMethod = classmethod[Any]
297
+ else:
298
+ # classmethod[TargetType, CallableParamSpecType, CallableReturnType]
299
+ AnyClassMethod = classmethod[Any, Any, Any]
300
+
301
+ __all__ = (
302
+ 'AnyCallable',
303
+ 'NoArgAnyCallable',
304
+ 'NoneType',
305
+ 'is_none_type',
306
+ 'display_as_type',
307
+ 'resolve_annotations',
308
+ 'is_callable_type',
309
+ 'is_literal_type',
310
+ 'all_literal_values',
311
+ 'is_namedtuple',
312
+ 'is_typeddict',
313
+ 'is_typeddict_special',
314
+ 'is_new_type',
315
+ 'new_type_supertype',
316
+ 'is_classvar',
317
+ 'is_finalvar',
318
+ 'update_field_forward_refs',
319
+ 'update_model_forward_refs',
320
+ 'TupleGenerator',
321
+ 'DictStrAny',
322
+ 'DictAny',
323
+ 'SetStr',
324
+ 'ListStr',
325
+ 'IntStr',
326
+ 'AbstractSetIntStr',
327
+ 'DictIntStrAny',
328
+ 'CallableGenerator',
329
+ 'ReprArgs',
330
+ 'AnyClassMethod',
331
+ 'CallableGenerator',
332
+ 'WithArgsTypes',
333
+ 'get_args',
334
+ 'get_origin',
335
+ 'get_sub_types',
336
+ 'typing_base',
337
+ 'get_all_type_hints',
338
+ 'is_union',
339
+ 'StrPath',
340
+ 'MappingIntStrAny',
341
+ )
342
+
343
+
344
+ NoneType = None.__class__
345
+
346
+
347
+ NONE_TYPES: Tuple[Any, Any, Any] = (None, NoneType, Literal[None])
348
+
349
+
350
+ if sys.version_info < (3, 8):
351
+ # Even though this implementation is slower, we need it for python 3.7:
352
+ # In python 3.7 "Literal" is not a builtin type and uses a different
353
+ # mechanism.
354
+ # for this reason `Literal[None] is Literal[None]` evaluates to `False`,
355
+ # breaking the faster implementation used for the other python versions.
356
+
357
+ def is_none_type(type_: Any) -> bool:
358
+ return type_ in NONE_TYPES
359
+
360
+ elif sys.version_info[:2] == (3, 8):
361
+
362
+ def is_none_type(type_: Any) -> bool:
363
+ for none_type in NONE_TYPES:
364
+ if type_ is none_type:
365
+ return True
366
+ # With python 3.8, specifically 3.8.10, Literal "is" check sare very flakey
367
+ # can change on very subtle changes like use of types in other modules,
368
+ # hopefully this check avoids that issue.
369
+ if is_literal_type(type_): # pragma: no cover
370
+ return all_literal_values(type_) == (None,)
371
+ return False
372
+
373
+ else:
374
+
375
+ def is_none_type(type_: Any) -> bool:
376
+ return type_ in NONE_TYPES
377
+
378
+
379
+ def display_as_type(v: Type[Any]) -> str:
380
+ if not isinstance(v, typing_base) and not isinstance(v, WithArgsTypes) and not isinstance(v, type):
381
+ v = v.__class__
382
+
383
+ if is_union(get_origin(v)):
384
+ return f'Union[{", ".join(map(display_as_type, get_args(v)))}]'
385
+
386
+ if isinstance(v, WithArgsTypes):
387
+ # Generic alias are constructs like `list[int]`
388
+ return str(v).replace('typing.', '')
389
+
390
+ try:
391
+ return v.__name__
392
+ except AttributeError:
393
+ # happens with typing objects
394
+ return str(v).replace('typing.', '')
395
+
396
+
397
+ def resolve_annotations(raw_annotations: Dict[str, Type[Any]], module_name: Optional[str]) -> Dict[str, Type[Any]]:
398
+ """
399
+ Partially taken from typing.get_type_hints.
400
+
401
+ Resolve string or ForwardRef annotations into type objects if possible.
402
+ """
403
+ base_globals: Optional[Dict[str, Any]] = None
404
+ if module_name:
405
+ try:
406
+ module = sys.modules[module_name]
407
+ except KeyError:
408
+ # happens occasionally, see https://github.com/pydantic/pydantic/issues/2363
409
+ pass
410
+ else:
411
+ base_globals = module.__dict__
412
+
413
+ annotations = {}
414
+ for name, value in raw_annotations.items():
415
+ if isinstance(value, str):
416
+ if (3, 10) > sys.version_info >= (3, 9, 8) or sys.version_info >= (3, 10, 1):
417
+ value = ForwardRef(value, is_argument=False, is_class=True)
418
+ else:
419
+ value = ForwardRef(value, is_argument=False)
420
+ try:
421
+ if sys.version_info >= (3, 13):
422
+ value = _eval_type(value, base_globals, None, type_params=())
423
+ else:
424
+ value = _eval_type(value, base_globals, None)
425
+ except NameError:
426
+ # this is ok, it can be fixed with update_forward_refs
427
+ pass
428
+ annotations[name] = value
429
+ return annotations
430
+
431
+
432
+ def is_callable_type(type_: Type[Any]) -> bool:
433
+ return type_ is Callable or get_origin(type_) is Callable
434
+
435
+
436
+ def is_literal_type(type_: Type[Any]) -> bool:
437
+ return Literal is not None and get_origin(type_) in LITERAL_TYPES
438
+
439
+
440
+ def literal_values(type_: Type[Any]) -> Tuple[Any, ...]:
441
+ return get_args(type_)
442
+
443
+
444
+ def all_literal_values(type_: Type[Any]) -> Tuple[Any, ...]:
445
+ """
446
+ This method is used to retrieve all Literal values as
447
+ Literal can be used recursively (see https://www.python.org/dev/peps/pep-0586)
448
+ e.g. `Literal[Literal[Literal[1, 2, 3], "foo"], 5, None]`
449
+ """
450
+ if not is_literal_type(type_):
451
+ return (type_,)
452
+
453
+ values = literal_values(type_)
454
+ return tuple(x for value in values for x in all_literal_values(value))
455
+
456
+
457
+ def is_namedtuple(type_: Type[Any]) -> bool:
458
+ """
459
+ Check if a given class is a named tuple.
460
+ It can be either a `typing.NamedTuple` or `collections.namedtuple`
461
+ """
462
+ from pboot_validator.v1.utils import lenient_issubclass
463
+
464
+ return lenient_issubclass(type_, tuple) and hasattr(type_, '_fields')
465
+
466
+
467
+ def is_typeddict(type_: Type[Any]) -> bool:
468
+ """
469
+ Check if a given class is a typed dict (from `typing` or `typing_extensions`)
470
+ In 3.10, there will be a public method (https://docs.python.org/3.10/library/typing.html#typing.is_typeddict)
471
+ """
472
+ from pboot_validator.v1.utils import lenient_issubclass
473
+
474
+ return lenient_issubclass(type_, dict) and hasattr(type_, '__total__')
475
+
476
+
477
+ def _check_typeddict_special(type_: Any) -> bool:
478
+ return type_ is TypedDictRequired or type_ is TypedDictNotRequired
479
+
480
+
481
+ def is_typeddict_special(type_: Any) -> bool:
482
+ """
483
+ Check if type is a TypedDict special form (Required or NotRequired).
484
+ """
485
+ return _check_typeddict_special(type_) or _check_typeddict_special(get_origin(type_))
486
+
487
+
488
+ test_type = NewType('test_type', str)
489
+
490
+
491
+ def is_new_type(type_: Type[Any]) -> bool:
492
+ """
493
+ Check whether type_ was created using typing.NewType
494
+ """
495
+ return isinstance(type_, test_type.__class__) and hasattr(type_, '__supertype__') # type: ignore
496
+
497
+
498
+ def new_type_supertype(type_: Type[Any]) -> Type[Any]:
499
+ while hasattr(type_, '__supertype__'):
500
+ type_ = type_.__supertype__
501
+ return type_
502
+
503
+
504
+ def _check_classvar(v: Optional[Type[Any]]) -> bool:
505
+ if v is None:
506
+ return False
507
+
508
+ return v.__class__ == ClassVar.__class__ and getattr(v, '_name', None) == 'ClassVar'
509
+
510
+
511
+ def _check_finalvar(v: Optional[Type[Any]]) -> bool:
512
+ """
513
+ Check if a given type is a `typing.Final` type.
514
+ """
515
+ if v is None:
516
+ return False
517
+
518
+ return v.__class__ == Final.__class__ and (sys.version_info < (3, 8) or getattr(v, '_name', None) == 'Final')
519
+
520
+
521
+ def is_classvar(ann_type: Type[Any]) -> bool:
522
+ if _check_classvar(ann_type) or _check_classvar(get_origin(ann_type)):
523
+ return True
524
+
525
+ # this is an ugly workaround for class vars that contain forward references and are therefore themselves
526
+ # forward references, see #3679
527
+ if ann_type.__class__ == ForwardRef and ann_type.__forward_arg__.startswith('ClassVar['):
528
+ return True
529
+
530
+ return False
531
+
532
+
533
+ def is_finalvar(ann_type: Type[Any]) -> bool:
534
+ return _check_finalvar(ann_type) or _check_finalvar(get_origin(ann_type))
535
+
536
+
537
+ def update_field_forward_refs(field: 'ModelField', globalns: Any, localns: Any) -> None:
538
+ """
539
+ Try to update ForwardRefs on fields based on this ModelField, globalns and localns.
540
+ """
541
+ prepare = False
542
+ if field.type_.__class__ == ForwardRef:
543
+ prepare = True
544
+ field.type_ = evaluate_forwardref(field.type_, globalns, localns or None)
545
+ if field.outer_type_.__class__ == ForwardRef:
546
+ prepare = True
547
+ field.outer_type_ = evaluate_forwardref(field.outer_type_, globalns, localns or None)
548
+ if prepare:
549
+ field.prepare()
550
+
551
+ if field.sub_fields:
552
+ for sub_f in field.sub_fields:
553
+ update_field_forward_refs(sub_f, globalns=globalns, localns=localns)
554
+
555
+ if field.discriminator_key is not None:
556
+ field.prepare_discriminated_union_sub_fields()
557
+
558
+
559
+ def update_model_forward_refs(
560
+ model: Type[Any],
561
+ fields: Iterable['ModelField'],
562
+ json_encoders: Dict[Union[Type[Any], str, ForwardRef], AnyCallable],
563
+ localns: 'DictStrAny',
564
+ exc_to_suppress: Tuple[Type[BaseException], ...] = (),
565
+ ) -> None:
566
+ """
567
+ Try to update model fields ForwardRefs based on model and localns.
568
+ """
569
+ if model.__module__ in sys.modules:
570
+ globalns = sys.modules[model.__module__].__dict__.copy()
571
+ else:
572
+ globalns = {}
573
+
574
+ globalns.setdefault(model.__name__, model)
575
+
576
+ for f in fields:
577
+ try:
578
+ update_field_forward_refs(f, globalns=globalns, localns=localns)
579
+ except exc_to_suppress:
580
+ pass
581
+
582
+ for key in set(json_encoders.keys()):
583
+ if isinstance(key, str):
584
+ fr: ForwardRef = ForwardRef(key)
585
+ elif isinstance(key, ForwardRef):
586
+ fr = key
587
+ else:
588
+ continue
589
+
590
+ try:
591
+ new_key = evaluate_forwardref(fr, globalns, localns or None)
592
+ except exc_to_suppress: # pragma: no cover
593
+ continue
594
+
595
+ json_encoders[new_key] = json_encoders.pop(key)
596
+
597
+
598
+ def get_class(type_: Type[Any]) -> Union[None, bool, Type[Any]]:
599
+ """
600
+ Tries to get the class of a Type[T] annotation. Returns True if Type is used
601
+ without brackets. Otherwise returns None.
602
+ """
603
+ if type_ is type:
604
+ return True
605
+
606
+ if get_origin(type_) is None:
607
+ return None
608
+
609
+ args = get_args(type_)
610
+ if not args or not isinstance(args[0], type):
611
+ return True
612
+ else:
613
+ return args[0]
614
+
615
+
616
+ def get_sub_types(tp: Any) -> List[Any]:
617
+ """
618
+ Return all the types that are allowed by type `tp`
619
+ `tp` can be a `Union` of allowed types or an `Annotated` type
620
+ """
621
+ origin = get_origin(tp)
622
+ if origin is Annotated:
623
+ return get_sub_types(get_args(tp)[0])
624
+ elif is_union(origin):
625
+ return [x for t in get_args(tp) for x in get_sub_types(t)]
626
+ else:
627
+ return [tp]