|
1 | | -from types import UnionType |
2 | 1 | from typing import Any, Optional, Union, get_args, get_origin |
3 | 2 |
|
| 3 | +try: |
| 4 | + from types import UnionType |
| 5 | +except ImportError: |
| 6 | + UnionType = None |
| 7 | + |
4 | 8 | from aws_lambda_powertools.utilities.idempotency.exceptions import ( |
5 | 9 | IdempotencyModelTypeError, |
6 | 10 | ) |
|
9 | 13 | def get_actual_type(model_type: Any) -> Any: |
10 | 14 | """ |
11 | 15 | Extract the actual type from a potentially Optional or Union type. |
12 | | -
|
13 | 16 | This function handles types that may be wrapped in Optional or Union, |
14 | 17 | including the Python 3.10+ Union syntax (Type | None). |
15 | | -
|
16 | 18 | Parameters |
17 | 19 | ---------- |
18 | 20 | model_type: Any |
19 | 21 | The type to analyze. Can be a simple type, Optional[Type], BaseModel, dataclass |
20 | 22 | Returns |
21 | 23 | ------- |
22 | 24 | The actual type without Optional or Union wrappers. |
23 | | -
|
24 | 25 | Raises: |
25 | 26 | IdempotencyModelTypeError: If the type specification is invalid |
26 | 27 | (e.g., Union with multiple non-None types). |
27 | 28 | """ |
28 | 29 | # Check if the type is Optional, Union, or the new Union syntax |
29 | | - if get_origin(model_type) in (Optional, Union, UnionType): |
| 30 | + if get_origin(model_type) in (Optional, Union) or (UnionType is not None and get_origin(model_type) is UnionType): |
30 | 31 | # Get the arguments of the type (e.g., for Optional[int], this would be (int, NoneType)) |
31 | 32 | args = get_args(model_type) |
32 | 33 |
|
|
0 commit comments