|
| 1 | +import sys |
| 2 | +from typing import Any, Optional, Union, get_args, get_origin |
| 3 | + |
| 4 | +# Conditionally import or define UnionType based on Python version |
| 5 | +if sys.version_info >= (3, 10): |
| 6 | + from types import UnionType # Available in Python 3.10+ |
| 7 | +else: |
| 8 | + UnionType = Union # Fallback for Python 3.8 and 3.9 |
| 9 | + |
| 10 | +from aws_lambda_powertools.utilities.idempotency.exceptions import ( |
| 11 | + IdempotencyModelTypeError, |
| 12 | +) |
| 13 | + |
| 14 | + |
| 15 | +def get_actual_type(model_type: Any) -> Any: |
| 16 | + """ |
| 17 | + Extract the actual type from a potentially Optional or Union type. |
| 18 | + This function handles types that may be wrapped in Optional or Union, |
| 19 | + including the Python 3.10+ Union syntax (Type | None). |
| 20 | + Parameters |
| 21 | + ---------- |
| 22 | + model_type: Any |
| 23 | + The type to analyze. Can be a simple type, Optional[Type], BaseModel, dataclass |
| 24 | + Returns |
| 25 | + ------- |
| 26 | + The actual type without Optional or Union wrappers. |
| 27 | + Raises: |
| 28 | + IdempotencyModelTypeError: If the type specification is invalid |
| 29 | + (e.g., Union with multiple non-None types). |
| 30 | + """ |
| 31 | + |
| 32 | + # Get the origin of the type (e.g., Union, Optional) |
| 33 | + origin = get_origin(model_type) |
| 34 | + |
| 35 | + # Check if type is Union, Optional, or UnionType (Python 3.10+) |
| 36 | + if origin in (Union, Optional) or (sys.version_info >= (3, 10) and origin in (Union, UnionType)): |
| 37 | + # Get type arguments |
| 38 | + args = get_args(model_type) |
| 39 | + |
| 40 | + # Filter out NoneType |
| 41 | + actual_type = _extract_non_none_types(args) |
| 42 | + |
| 43 | + # Ensure only one non-None type exists |
| 44 | + if len(actual_type) != 1: |
| 45 | + raise IdempotencyModelTypeError( |
| 46 | + "Invalid type: expected a single type, optionally wrapped in Optional or Union with None.", |
| 47 | + ) |
| 48 | + |
| 49 | + return actual_type[0] |
| 50 | + |
| 51 | + # If not a Union/Optional type, return original type |
| 52 | + return model_type |
| 53 | + |
| 54 | + |
| 55 | +def _extract_non_none_types(args: tuple) -> list: |
| 56 | + """Extract non-None types from type arguments.""" |
| 57 | + return [arg for arg in args if arg is not type(None)] |
0 commit comments