Skip to content

Commit 05a96d8

Browse files
Making it work in python 3.8 and 3.9
1 parent cb60c14 commit 05a96d8

File tree

1 file changed

+23
-10
lines changed
  • aws_lambda_powertools/utilities/idempotency/serialization

1 file changed

+23
-10
lines changed

aws_lambda_powertools/utilities/idempotency/serialization/functions.py

Lines changed: 23 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,11 @@
1+
import sys
12
from typing import Any, Optional, Union, get_args, get_origin
23

3-
try:
4-
from types import UnionType
5-
except ImportError:
6-
UnionType = None # type: ignore[assignment, misc]
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
79

810
from aws_lambda_powertools.utilities.idempotency.exceptions import (
911
IdempotencyModelTypeError,
@@ -26,19 +28,30 @@ def get_actual_type(model_type: Any) -> Any:
2628
IdempotencyModelTypeError: If the type specification is invalid
2729
(e.g., Union with multiple non-None types).
2830
"""
29-
# Check if the type is Optional, Union, or the new Union syntax
30-
if get_origin(model_type) in (Optional, Union) or (UnionType is not None and get_origin(model_type) is UnionType):
31-
# Get the arguments of the type (e.g., for Optional[int], this would be (int, NoneType))
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 isinstance(origin, UnionType)):
37+
# Get type arguments
3238
args = get_args(model_type)
3339

34-
# Filter out NoneType to get the actual type(s)
35-
actual_type = [arg for arg in args if arg is not type(None)]
40+
# Filter out NoneType
41+
actual_type = _extract_non_none_types(args)
3642

37-
# Ensure there's exactly one non-None type
43+
# Ensure only one non-None type exists
3844
if len(actual_type) != 1:
3945
raise IdempotencyModelTypeError(
4046
"Invalid type: expected a single type, optionally wrapped in Optional or Union with None.",
4147
)
48+
4249
return actual_type[0]
4350

51+
# If not a Union/Optional type, return original type
4452
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

Comments
 (0)