|
17 | 17 | import re |
18 | 18 | import typing |
19 | 19 | import typeguard # type: ignore |
20 | | -import inspect |
21 | 20 | import shlex |
| 21 | +import collections.abc |
| 22 | +from inspect import isclass |
22 | 23 | from typing import ( |
23 | 24 | Callable, |
24 | 25 | List, |
@@ -149,21 +150,33 @@ def _transform_value(key: Any, value: Any) -> Any: |
149 | 150 | if not ann: |
150 | 151 | return value |
151 | 152 |
|
152 | | - if inspect.isclass(ann) and issubclass(ann, ImmutableValidatedObject): |
| 153 | + if isclass(ann) and issubclass(ann, ImmutableValidatedObject): |
153 | 154 | value = ann(**value) |
154 | 155 |
|
155 | | - # Support Sequence[ImmutableValidatedObject] |
156 | | - if isinstance(value, tuple) and not isinstance(ann, str): |
157 | | - new_value = [] |
158 | | - for v in value: |
159 | | - for subann in ann.__args__: # type: ignore |
160 | | - if inspect.isclass(subann) and issubclass( |
161 | | - subann, ImmutableValidatedObject |
162 | | - ): |
163 | | - new_value.append(subann(**v)) |
164 | | - else: |
165 | | - new_value.append(v) |
166 | | - value = tuple(new_value) |
| 156 | + # Support containers of ImmutableValidatedObjects |
| 157 | + match typing.get_origin(ann): |
| 158 | + |
| 159 | + case collections.abc.Sequence: |
| 160 | + sequence: List = [] |
| 161 | + for v in value: |
| 162 | + for subann in typing.get_args(ann): |
| 163 | + if isclass(subann) and issubclass( |
| 164 | + subann, ImmutableValidatedObject |
| 165 | + ): |
| 166 | + sequence.append(subann(**v)) |
| 167 | + else: |
| 168 | + sequence.append(v) |
| 169 | + value = tuple(sequence) |
| 170 | + |
| 171 | + case collections.abc.Mapping: |
| 172 | + _, value_ann = typing.get_args(ann) |
| 173 | + if isclass(value_ann) and issubclass( |
| 174 | + value_ann, ImmutableValidatedObject |
| 175 | + ): |
| 176 | + mapping: Dict = {} |
| 177 | + for k, v in value.items(): |
| 178 | + mapping[k] = value_ann(**v) |
| 179 | + value = mapping |
167 | 180 |
|
168 | 181 | typeguard.check_type(value, ann) |
169 | 182 |
|
|
0 commit comments