From b2cfc37557f97beda3111eab8d3d32ab0f6244a5 Mon Sep 17 00:00:00 2001 From: Bashir ABDEL WAHED Date: Tue, 12 Nov 2024 14:18:15 +0100 Subject: [PATCH] fix: :bug: typing with py310 Union | --- tawazi/node/helpers.py | 2 ++ ...est_multiple_return_value_for_exec_node.py | 33 +++++++++++++++++++ 2 files changed, 35 insertions(+) diff --git a/tawazi/node/helpers.py b/tawazi/node/helpers.py index c07833aa..36c61748 100644 --- a/tawazi/node/helpers.py +++ b/tawazi/node/helpers.py @@ -22,6 +22,8 @@ def _validate_tuple(func: Callable[..., Any], unpack_to: int) -> Optional[bool]: if isinstance(r_type, str): # eval is safe to use because the user is providing the typing and evaluating it locally r_type = eval(r_type, func.__globals__) # noqa: PGH001,S307 # nosec B307 + if not hasattr(r_type, "__origin__"): + return None is_tuple = r_type.__origin__ is tuple if not is_tuple: return None diff --git a/tests/test_multiple_return_value_for_exec_node.py b/tests/test_multiple_return_value_for_exec_node.py index 801beba6..9c4b766e 100644 --- a/tests/test_multiple_return_value_for_exec_node.py +++ b/tests/test_multiple_return_value_for_exec_node.py @@ -1,3 +1,4 @@ +import sys from typing import Dict, List, Tuple import pytest @@ -219,3 +220,35 @@ def pipe() -> Tuple[int, int, int, List[int]]: return r1, r2, r3, list_v assert pipe() == (1, 2, 3, [1, 2, 3]) + + +# if python version is 3.10 or higher, include this function +if sys.version_info >= (3, 10): + from typing import Union + + from tawazi import xn + + union_type = Union[tuple[float, int], tuple[float, float]] + py311_union_type = tuple[float, int] | tuple[float, float] + + @xn(unpack_to=2) + def union_py39(x: float, integer: bool = False) -> union_type: + return x, x / 2 if not integer else int(x / 2) + + @dag + def dag_union_py39(x): + return union_py39(x) + + def test_unpacking_union() -> None: + assert 1, 1 / 2 == dag_union_py39(1) + + @xn(unpack_to=2) + def union_py310(x: float, integer: bool = False) -> py311_union_type: + return x, x / 2 if not integer else int(x / 2) + + @dag + def dag_union_py310(x): + return union_py310(x) + + def test_unpacking_union_py310() -> None: + assert 2, 1 == dag_union_py310(2)