|
| 1 | +from typing import TYPE_CHECKING |
| 2 | +from typing import Any |
| 3 | +from typing import Callable |
| 4 | +from typing import List |
| 5 | + |
| 6 | +from openapi_core.casting.schemas.datatypes import CasterCallable |
1 | 7 | from openapi_core.casting.schemas.exceptions import CastError
|
| 8 | +from openapi_core.spec import Spec |
| 9 | + |
| 10 | +if TYPE_CHECKING: |
| 11 | + from openapi_core.casting.schemas.factories import SchemaCastersFactory |
2 | 12 |
|
3 | 13 |
|
4 | 14 | class BaseSchemaCaster:
|
5 |
| - def __init__(self, schema): |
| 15 | + def __init__(self, schema: Spec): |
6 | 16 | self.schema = schema
|
7 | 17 |
|
8 |
| - def __call__(self, value): |
| 18 | + def __call__(self, value: Any) -> Any: |
9 | 19 | if value is None:
|
10 | 20 | return value
|
11 | 21 |
|
12 | 22 | return self.cast(value)
|
13 | 23 |
|
14 |
| - def cast(self, value): |
| 24 | + def cast(self, value: Any) -> Any: |
15 | 25 | raise NotImplementedError
|
16 | 26 |
|
17 | 27 |
|
18 | 28 | class CallableSchemaCaster(BaseSchemaCaster):
|
19 |
| - def __init__(self, schema, caster_callable): |
| 29 | + def __init__(self, schema: Spec, caster_callable: CasterCallable): |
20 | 30 | super().__init__(schema)
|
21 | 31 | self.caster_callable = caster_callable
|
22 | 32 |
|
23 |
| - def cast(self, value): |
| 33 | + def cast(self, value: Any) -> Any: |
24 | 34 | try:
|
25 | 35 | return self.caster_callable(value)
|
26 | 36 | except (ValueError, TypeError):
|
27 | 37 | raise CastError(value, self.schema["type"])
|
28 | 38 |
|
29 | 39 |
|
30 | 40 | class DummyCaster(BaseSchemaCaster):
|
31 |
| - def cast(self, value): |
| 41 | + def cast(self, value: Any) -> Any: |
32 | 42 | return value
|
33 | 43 |
|
34 | 44 |
|
35 | 45 | class ComplexCaster(BaseSchemaCaster):
|
36 |
| - def __init__(self, schema, casters_factory): |
| 46 | + def __init__(self, schema: Spec, casters_factory: "SchemaCastersFactory"): |
37 | 47 | super().__init__(schema)
|
38 | 48 | self.casters_factory = casters_factory
|
39 | 49 |
|
40 | 50 |
|
41 | 51 | class ArrayCaster(ComplexCaster):
|
42 | 52 | @property
|
43 |
| - def items_caster(self): |
| 53 | + def items_caster(self) -> BaseSchemaCaster: |
44 | 54 | return self.casters_factory.create(self.schema / "items")
|
45 | 55 |
|
46 |
| - def cast(self, value): |
| 56 | + def cast(self, value: Any) -> List[Any]: |
47 | 57 | try:
|
48 | 58 | return list(map(self.items_caster, value))
|
49 | 59 | except (ValueError, TypeError):
|
|
0 commit comments