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,400 @@
1
+ import functools
2
+ import operator
3
+ import sys
4
+ import types
5
+ import typing
6
+ from typing import (
7
+ TYPE_CHECKING,
8
+ Any,
9
+ ClassVar,
10
+ Dict,
11
+ ForwardRef,
12
+ Generic,
13
+ Iterator,
14
+ List,
15
+ Mapping,
16
+ Optional,
17
+ Tuple,
18
+ Type,
19
+ TypeVar,
20
+ Union,
21
+ cast,
22
+ )
23
+ from weakref import WeakKeyDictionary, WeakValueDictionary
24
+
25
+ from typing_extensions import Annotated, Literal as ExtLiteral
26
+
27
+ from pboot_validator.v1.class_validators import gather_all_validators
28
+ from pboot_validator.v1.fields import DeferredType
29
+ from pboot_validator.v1.main import BaseModel, create_model
30
+ from pboot_validator.v1.types import JsonWrapper
31
+ from pboot_validator.v1.typing import display_as_type, get_all_type_hints, get_args, get_origin, typing_base
32
+ from pboot_validator.v1.utils import all_identical, lenient_issubclass
33
+
34
+ if sys.version_info >= (3, 8):
35
+ from typing import Literal
36
+
37
+ GenericModelT = TypeVar('GenericModelT', bound='GenericModel')
38
+ TypeVarType = Any # since mypy doesn't allow the use of TypeVar as a type
39
+
40
+ CacheKey = Tuple[Type[Any], Any, Tuple[Any, ...]]
41
+ Parametrization = Mapping[TypeVarType, Type[Any]]
42
+
43
+ # weak dictionaries allow the dynamically created parametrized versions of generic models to get collected
44
+ # once they are no longer referenced by the caller.
45
+ if sys.version_info >= (3, 9): # Typing for weak dictionaries available at 3.9
46
+ GenericTypesCache = WeakValueDictionary[CacheKey, Type[BaseModel]]
47
+ AssignedParameters = WeakKeyDictionary[Type[BaseModel], Parametrization]
48
+ else:
49
+ GenericTypesCache = WeakValueDictionary
50
+ AssignedParameters = WeakKeyDictionary
51
+
52
+ # _generic_types_cache is a Mapping from __class_getitem__ arguments to the parametrized version of generic models.
53
+ # This ensures multiple calls of e.g. A[B] return always the same class.
54
+ _generic_types_cache = GenericTypesCache()
55
+
56
+ # _assigned_parameters is a Mapping from parametrized version of generic models to assigned types of parametrizations
57
+ # as captured during construction of the class (not instances).
58
+ # E.g., for generic model `Model[A, B]`, when parametrized model `Model[int, str]` is created,
59
+ # `Model[int, str]`: {A: int, B: str}` will be stored in `_assigned_parameters`.
60
+ # (This information is only otherwise available after creation from the class name string).
61
+ _assigned_parameters = AssignedParameters()
62
+
63
+
64
+ class GenericModel(BaseModel):
65
+ __slots__ = ()
66
+ __concrete__: ClassVar[bool] = False
67
+
68
+ if TYPE_CHECKING:
69
+ # Putting this in a TYPE_CHECKING block allows us to replace `if Generic not in cls.__bases__` with
70
+ # `not hasattr(cls, "__parameters__")`. This means we don't need to force non-concrete subclasses of
71
+ # `GenericModel` to also inherit from `Generic`, which would require changes to the use of `create_model` below.
72
+ __parameters__: ClassVar[Tuple[TypeVarType, ...]]
73
+
74
+ # Setting the return type as Type[Any] instead of Type[BaseModel] prevents PyCharm warnings
75
+ def __class_getitem__(cls: Type[GenericModelT], params: Union[Type[Any], Tuple[Type[Any], ...]]) -> Type[Any]:
76
+ """Instantiates a new class from a generic class `cls` and type variables `params`.
77
+
78
+ :param params: Tuple of types the class . Given a generic class
79
+ `Model` with 2 type variables and a concrete model `Model[str, int]`,
80
+ the value `(str, int)` would be passed to `params`.
81
+ :return: New model class inheriting from `cls` with instantiated
82
+ types described by `params`. If no parameters are given, `cls` is
83
+ returned as is.
84
+
85
+ """
86
+
87
+ def _cache_key(_params: Any) -> CacheKey:
88
+ args = get_args(_params)
89
+ # python returns a list for Callables, which is not hashable
90
+ if len(args) == 2 and isinstance(args[0], list):
91
+ args = (tuple(args[0]), args[1])
92
+ return cls, _params, args
93
+
94
+ cached = _generic_types_cache.get(_cache_key(params))
95
+ if cached is not None:
96
+ return cached
97
+ if cls.__concrete__ and Generic not in cls.__bases__:
98
+ raise TypeError('Cannot parameterize a concrete instantiation of a generic model')
99
+ if not isinstance(params, tuple):
100
+ params = (params,)
101
+ if cls is GenericModel and any(isinstance(param, TypeVar) for param in params):
102
+ raise TypeError('Type parameters should be placed on typing.Generic, not GenericModel')
103
+ if not hasattr(cls, '__parameters__'):
104
+ raise TypeError(f'Type {cls.__name__} must inherit from typing.Generic before being parameterized')
105
+
106
+ check_parameters_count(cls, params)
107
+ # Build map from generic typevars to passed params
108
+ typevars_map: Dict[TypeVarType, Type[Any]] = dict(zip(cls.__parameters__, params))
109
+ if all_identical(typevars_map.keys(), typevars_map.values()) and typevars_map:
110
+ return cls # if arguments are equal to parameters it's the same object
111
+
112
+ # Create new model with original model as parent inserting fields with DeferredType.
113
+ model_name = cls.__concrete_name__(params)
114
+ validators = gather_all_validators(cls)
115
+
116
+ type_hints = get_all_type_hints(cls).items()
117
+ instance_type_hints = {k: v for k, v in type_hints if get_origin(v) is not ClassVar}
118
+
119
+ fields = {k: (DeferredType(), cls.__fields__[k].field_info) for k in instance_type_hints if k in cls.__fields__}
120
+
121
+ model_module, called_globally = get_caller_frame_info()
122
+ created_model = cast(
123
+ Type[GenericModel], # casting ensures mypy is aware of the __concrete__ and __parameters__ attributes
124
+ create_model(
125
+ model_name,
126
+ __module__=model_module or cls.__module__,
127
+ __base__=(cls,) + tuple(cls.__parameterized_bases__(typevars_map)),
128
+ __config__=None,
129
+ __validators__=validators,
130
+ __cls_kwargs__=None,
131
+ **fields,
132
+ ),
133
+ )
134
+
135
+ _assigned_parameters[created_model] = typevars_map
136
+
137
+ if called_globally: # create global reference and therefore allow pickling
138
+ object_by_reference = None
139
+ reference_name = model_name
140
+ reference_module_globals = sys.modules[created_model.__module__].__dict__
141
+ while object_by_reference is not created_model:
142
+ object_by_reference = reference_module_globals.setdefault(reference_name, created_model)
143
+ reference_name += '_'
144
+
145
+ created_model.Config = cls.Config
146
+
147
+ # Find any typevars that are still present in the model.
148
+ # If none are left, the model is fully "concrete", otherwise the new
149
+ # class is a generic class as well taking the found typevars as
150
+ # parameters.
151
+ new_params = tuple(
152
+ {param: None for param in iter_contained_typevars(typevars_map.values())}
153
+ ) # use dict as ordered set
154
+ created_model.__concrete__ = not new_params
155
+ if new_params:
156
+ created_model.__parameters__ = new_params
157
+
158
+ # Save created model in cache so we don't end up creating duplicate
159
+ # models that should be identical.
160
+ _generic_types_cache[_cache_key(params)] = created_model
161
+ if len(params) == 1:
162
+ _generic_types_cache[_cache_key(params[0])] = created_model
163
+
164
+ # Recursively walk class type hints and replace generic typevars
165
+ # with concrete types that were passed.
166
+ _prepare_model_fields(created_model, fields, instance_type_hints, typevars_map)
167
+
168
+ return created_model
169
+
170
+ @classmethod
171
+ def __concrete_name__(cls: Type[Any], params: Tuple[Type[Any], ...]) -> str:
172
+ """Compute class name for child classes.
173
+
174
+ :param params: Tuple of types the class . Given a generic class
175
+ `Model` with 2 type variables and a concrete model `Model[str, int]`,
176
+ the value `(str, int)` would be passed to `params`.
177
+ :return: String representing a the new class where `params` are
178
+ passed to `cls` as type variables.
179
+
180
+ This method can be overridden to achieve a custom naming scheme for GenericModels.
181
+ """
182
+ param_names = [display_as_type(param) for param in params]
183
+ params_component = ', '.join(param_names)
184
+ return f'{cls.__name__}[{params_component}]'
185
+
186
+ @classmethod
187
+ def __parameterized_bases__(cls, typevars_map: Parametrization) -> Iterator[Type[Any]]:
188
+ """
189
+ Returns unbound bases of cls parameterised to given type variables
190
+
191
+ :param typevars_map: Dictionary of type applications for binding subclasses.
192
+ Given a generic class `Model` with 2 type variables [S, T]
193
+ and a concrete model `Model[str, int]`,
194
+ the value `{S: str, T: int}` would be passed to `typevars_map`.
195
+ :return: an iterator of generic sub classes, parameterised by `typevars_map`
196
+ and other assigned parameters of `cls`
197
+
198
+ e.g.:
199
+ ```
200
+ class A(GenericModel, Generic[T]):
201
+ ...
202
+
203
+ class B(A[V], Generic[V]):
204
+ ...
205
+
206
+ assert A[int] in B.__parameterized_bases__({V: int})
207
+ ```
208
+ """
209
+
210
+ def build_base_model(
211
+ base_model: Type[GenericModel], mapped_types: Parametrization
212
+ ) -> Iterator[Type[GenericModel]]:
213
+ base_parameters = tuple(mapped_types[param] for param in base_model.__parameters__)
214
+ parameterized_base = base_model.__class_getitem__(base_parameters)
215
+ if parameterized_base is base_model or parameterized_base is cls:
216
+ # Avoid duplication in MRO
217
+ return
218
+ yield parameterized_base
219
+
220
+ for base_model in cls.__bases__:
221
+ if not issubclass(base_model, GenericModel):
222
+ # not a class that can be meaningfully parameterized
223
+ continue
224
+ elif not getattr(base_model, '__parameters__', None):
225
+ # base_model is "GenericModel" (and has no __parameters__)
226
+ # or
227
+ # base_model is already concrete, and will be included transitively via cls.
228
+ continue
229
+ elif cls in _assigned_parameters:
230
+ if base_model in _assigned_parameters:
231
+ # cls is partially parameterised but not from base_model
232
+ # e.g. cls = B[S], base_model = A[S]
233
+ # B[S][int] should subclass A[int], (and will be transitively via B[int])
234
+ # but it's not viable to consistently subclass types with arbitrary construction
235
+ # So don't attempt to include A[S][int]
236
+ continue
237
+ else: # base_model not in _assigned_parameters:
238
+ # cls is partially parameterized, base_model is original generic
239
+ # e.g. cls = B[str, T], base_model = B[S, T]
240
+ # Need to determine the mapping for the base_model parameters
241
+ mapped_types: Parametrization = {
242
+ key: typevars_map.get(value, value) for key, value in _assigned_parameters[cls].items()
243
+ }
244
+ yield from build_base_model(base_model, mapped_types)
245
+ else:
246
+ # cls is base generic, so base_class has a distinct base
247
+ # can construct the Parameterised base model using typevars_map directly
248
+ yield from build_base_model(base_model, typevars_map)
249
+
250
+
251
+ def replace_types(type_: Any, type_map: Mapping[Any, Any]) -> Any:
252
+ """Return type with all occurrences of `type_map` keys recursively replaced with their values.
253
+
254
+ :param type_: Any type, class or generic alias
255
+ :param type_map: Mapping from `TypeVar` instance to concrete types.
256
+ :return: New type representing the basic structure of `type_` with all
257
+ `typevar_map` keys recursively replaced.
258
+
259
+ >>> replace_types(Tuple[str, Union[List[str], float]], {str: int})
260
+ Tuple[int, Union[List[int], float]]
261
+
262
+ """
263
+ if not type_map:
264
+ return type_
265
+
266
+ type_args = get_args(type_)
267
+ origin_type = get_origin(type_)
268
+
269
+ if origin_type is Annotated:
270
+ annotated_type, *annotations = type_args
271
+ return Annotated[replace_types(annotated_type, type_map), tuple(annotations)]
272
+
273
+ if (origin_type is ExtLiteral) or (sys.version_info >= (3, 8) and origin_type is Literal):
274
+ return type_map.get(type_, type_)
275
+ # Having type args is a good indicator that this is a typing module
276
+ # class instantiation or a generic alias of some sort.
277
+ if type_args:
278
+ resolved_type_args = tuple(replace_types(arg, type_map) for arg in type_args)
279
+ if all_identical(type_args, resolved_type_args):
280
+ # If all arguments are the same, there is no need to modify the
281
+ # type or create a new object at all
282
+ return type_
283
+ if (
284
+ origin_type is not None
285
+ and isinstance(type_, typing_base)
286
+ and not isinstance(origin_type, typing_base)
287
+ and getattr(type_, '_name', None) is not None
288
+ ):
289
+ # In python < 3.9 generic aliases don't exist so any of these like `list`,
290
+ # `type` or `collections.abc.Callable` need to be translated.
291
+ # See: https://www.python.org/dev/peps/pep-0585
292
+ origin_type = getattr(typing, type_._name)
293
+ assert origin_type is not None
294
+ # PEP-604 syntax (Ex.: list | str) is represented with a types.UnionType object that does not have __getitem__.
295
+ # We also cannot use isinstance() since we have to compare types.
296
+ if sys.version_info >= (3, 10) and origin_type is types.UnionType: # noqa: E721
297
+ return functools.reduce(operator.or_, resolved_type_args)
298
+ return origin_type[resolved_type_args]
299
+
300
+ # We handle pydantic generic models separately as they don't have the same
301
+ # semantics as "typing" classes or generic aliases
302
+ if not origin_type and lenient_issubclass(type_, GenericModel) and not type_.__concrete__:
303
+ type_args = type_.__parameters__
304
+ resolved_type_args = tuple(replace_types(t, type_map) for t in type_args)
305
+ if all_identical(type_args, resolved_type_args):
306
+ return type_
307
+ return type_[resolved_type_args]
308
+
309
+ # Handle special case for typehints that can have lists as arguments.
310
+ # `typing.Callable[[int, str], int]` is an example for this.
311
+ if isinstance(type_, (List, list)):
312
+ resolved_list = list(replace_types(element, type_map) for element in type_)
313
+ if all_identical(type_, resolved_list):
314
+ return type_
315
+ return resolved_list
316
+
317
+ # For JsonWrapperValue, need to handle its inner type to allow correct parsing
318
+ # of generic Json arguments like Json[T]
319
+ if not origin_type and lenient_issubclass(type_, JsonWrapper):
320
+ type_.inner_type = replace_types(type_.inner_type, type_map)
321
+ return type_
322
+
323
+ # If all else fails, we try to resolve the type directly and otherwise just
324
+ # return the input with no modifications.
325
+ new_type = type_map.get(type_, type_)
326
+ # Convert string to ForwardRef
327
+ if isinstance(new_type, str):
328
+ return ForwardRef(new_type)
329
+ else:
330
+ return new_type
331
+
332
+
333
+ def check_parameters_count(cls: Type[GenericModel], parameters: Tuple[Any, ...]) -> None:
334
+ actual = len(parameters)
335
+ expected = len(cls.__parameters__)
336
+ if actual != expected:
337
+ description = 'many' if actual > expected else 'few'
338
+ raise TypeError(f'Too {description} parameters for {cls.__name__}; actual {actual}, expected {expected}')
339
+
340
+
341
+ DictValues: Type[Any] = {}.values().__class__
342
+
343
+
344
+ def iter_contained_typevars(v: Any) -> Iterator[TypeVarType]:
345
+ """Recursively iterate through all subtypes and type args of `v` and yield any typevars that are found."""
346
+ if isinstance(v, TypeVar):
347
+ yield v
348
+ elif hasattr(v, '__parameters__') and not get_origin(v) and lenient_issubclass(v, GenericModel):
349
+ yield from v.__parameters__
350
+ elif isinstance(v, (DictValues, list)):
351
+ for var in v:
352
+ yield from iter_contained_typevars(var)
353
+ else:
354
+ args = get_args(v)
355
+ for arg in args:
356
+ yield from iter_contained_typevars(arg)
357
+
358
+
359
+ def get_caller_frame_info() -> Tuple[Optional[str], bool]:
360
+ """
361
+ Used inside a function to check whether it was called globally
362
+
363
+ Will only work against non-compiled code, therefore used only in pboot_validator.generics
364
+
365
+ :returns Tuple[module_name, called_globally]
366
+ """
367
+ try:
368
+ previous_caller_frame = sys._getframe(2)
369
+ except ValueError as e:
370
+ raise RuntimeError('This function must be used inside another function') from e
371
+ except AttributeError: # sys module does not have _getframe function, so there's nothing we can do about it
372
+ return None, False
373
+ frame_globals = previous_caller_frame.f_globals
374
+ return frame_globals.get('__name__'), previous_caller_frame.f_locals is frame_globals
375
+
376
+
377
+ def _prepare_model_fields(
378
+ created_model: Type[GenericModel],
379
+ fields: Mapping[str, Any],
380
+ instance_type_hints: Mapping[str, type],
381
+ typevars_map: Mapping[Any, type],
382
+ ) -> None:
383
+ """
384
+ Replace DeferredType fields with concrete type hints and prepare them.
385
+ """
386
+
387
+ for key, field in created_model.__fields__.items():
388
+ if key not in fields:
389
+ assert field.type_.__class__ is not DeferredType
390
+ # https://github.com/nedbat/coveragepy/issues/198
391
+ continue # pragma: no cover
392
+
393
+ assert field.type_.__class__ is DeferredType, field.type_.__class__
394
+
395
+ field_type_hint = instance_type_hints[key]
396
+ concrete_type = replace_types(field_type_hint, typevars_map)
397
+ field.type_ = concrete_type
398
+ field.outer_type_ = concrete_type
399
+ field.prepare()
400
+ created_model.__annotations__[key] = concrete_type
@@ -0,0 +1,112 @@
1
+ import datetime
2
+ from collections import deque
3
+ from decimal import Decimal
4
+ from enum import Enum
5
+ from ipaddress import IPv4Address, IPv4Interface, IPv4Network, IPv6Address, IPv6Interface, IPv6Network
6
+ from pathlib import Path
7
+ from re import Pattern
8
+ from types import GeneratorType
9
+ from typing import Any, Callable, Dict, Type, Union
10
+ from uuid import UUID
11
+
12
+ from pboot_validator.v1.color import Color
13
+ from pboot_validator.v1.networks import NameEmail
14
+ from pboot_validator.v1.types import SecretBytes, SecretStr
15
+
16
+ __all__ = 'pydantic_encoder', 'custom_pydantic_encoder', 'timedelta_isoformat'
17
+
18
+
19
+ def isoformat(o: Union[datetime.date, datetime.time]) -> str:
20
+ return o.isoformat()
21
+
22
+
23
+ def decimal_encoder(dec_value: Decimal) -> Union[int, float]:
24
+ """
25
+ Encodes a Decimal as int of there's no exponent, otherwise float
26
+
27
+ This is useful when we use ConstrainedDecimal to represent Numeric(x,0)
28
+ where a integer (but not int typed) is used. Encoding this as a float
29
+ results in failed round-tripping between encode and parse.
30
+ Our Id type is a prime example of this.
31
+
32
+ >>> decimal_encoder(Decimal("1.0"))
33
+ 1.0
34
+
35
+ >>> decimal_encoder(Decimal("1"))
36
+ 1
37
+ """
38
+ if dec_value.as_tuple().exponent >= 0:
39
+ return int(dec_value)
40
+ else:
41
+ return float(dec_value)
42
+
43
+
44
+ ENCODERS_BY_TYPE: Dict[Type[Any], Callable[[Any], Any]] = {
45
+ bytes: lambda o: o.decode(),
46
+ Color: str,
47
+ datetime.date: isoformat,
48
+ datetime.datetime: isoformat,
49
+ datetime.time: isoformat,
50
+ datetime.timedelta: lambda td: td.total_seconds(),
51
+ Decimal: decimal_encoder,
52
+ Enum: lambda o: o.value,
53
+ frozenset: list,
54
+ deque: list,
55
+ GeneratorType: list,
56
+ IPv4Address: str,
57
+ IPv4Interface: str,
58
+ IPv4Network: str,
59
+ IPv6Address: str,
60
+ IPv6Interface: str,
61
+ IPv6Network: str,
62
+ NameEmail: str,
63
+ Path: str,
64
+ Pattern: lambda o: o.pattern,
65
+ SecretBytes: str,
66
+ SecretStr: str,
67
+ set: list,
68
+ UUID: str,
69
+ }
70
+
71
+
72
+ def pydantic_encoder(obj: Any) -> Any:
73
+ from dataclasses import asdict, is_dataclass
74
+
75
+ from pboot_validator.v1.main import BaseModel
76
+
77
+ if isinstance(obj, BaseModel):
78
+ return obj.dict()
79
+ elif is_dataclass(obj):
80
+ return asdict(obj)
81
+
82
+ # Check the class type and its superclasses for a matching encoder
83
+ for base in obj.__class__.__mro__[:-1]:
84
+ try:
85
+ encoder = ENCODERS_BY_TYPE[base]
86
+ except KeyError:
87
+ continue
88
+ return encoder(obj)
89
+ else: # We have exited the for loop without finding a suitable encoder
90
+ raise TypeError(f"Object of type '{obj.__class__.__name__}' is not JSON serializable")
91
+
92
+
93
+ def custom_pydantic_encoder(type_encoders: Dict[Any, Callable[[Type[Any]], Any]], obj: Any) -> Any:
94
+ # Check the class type and its superclasses for a matching encoder
95
+ for base in obj.__class__.__mro__[:-1]:
96
+ try:
97
+ encoder = type_encoders[base]
98
+ except KeyError:
99
+ continue
100
+
101
+ return encoder(obj)
102
+ else: # We have exited the for loop without finding a suitable encoder
103
+ return pydantic_encoder(obj)
104
+
105
+
106
+ def timedelta_isoformat(td: datetime.timedelta) -> str:
107
+ """
108
+ ISO 8601 encoding for Python timedelta object.
109
+ """
110
+ minutes, seconds = divmod(td.seconds, 60)
111
+ hours, minutes = divmod(minutes, 60)
112
+ return f'{"-" if td.days < 0 else ""}P{abs(td.days)}DT{hours:d}H{minutes:d}M{seconds:d}.{td.microseconds:06d}S'