From 613effa15cbe4417d60333a4212ce519c893a96e Mon Sep 17 00:00:00 2001 From: aranega Date: Fri, 25 Oct 2024 18:16:12 -0600 Subject: [PATCH] Fix use of union notation for Python < 3.10 --- iguala/helpers.py | 16 +++++++++++++--- tests/test_object_matchers.py | 3 +++ 2 files changed, 16 insertions(+), 3 deletions(-) diff --git a/iguala/helpers.py b/iguala/helpers.py index 466cbe5..65d51fb 100644 --- a/iguala/helpers.py +++ b/iguala/helpers.py @@ -1,14 +1,24 @@ -from __future__ import annotations from collections.abc import MutableSet from itertools import chain -from types import UnionType + +try: + from types import UnionType + + def is_union(o): + return isinstance(o, UnionType) + +except ImportError: + from typing import Union, get_origin + + def is_union(o): + return get_origin(o) is Union class match(object): def __init__(self, cls, *classes): from .matchers import ObjectMatcher - if isinstance(cls, UnionType): + if is_union(cls): all_classes = cls.__args__ else: all_classes = [cls, *classes] diff --git a/tests/test_object_matchers.py b/tests/test_object_matchers.py index 35ba644..2e37bbb 100644 --- a/tests/test_object_matchers.py +++ b/tests/test_object_matchers.py @@ -1,4 +1,6 @@ +import pytest from iguala import as_matcher, match +import sys from .data_for_tests import ATest, BTest, InnerTest, obj_test @@ -145,6 +147,7 @@ def test_match_multiple_types(): assert pattern.match(BTest(0, 0, 'foo', InnerTest('bar', 5), [], 5)).is_match is True +@pytest.mark.skipif(sys.version_info < (3, 10), reason="Union notation is not available for Python < 3.10") def test_match_union_type(): pattern = match(ATest) % {} assert pattern.match(BTest(0, 0, 'foo', InnerTest('bar', 5), [], 5)).is_match is False