From 1a1b5aac2cf083a6e26f13b3684a62775c628061 Mon Sep 17 00:00:00 2001 From: thatmattlove Date: Thu, 16 Sep 2021 15:57:12 -0700 Subject: [PATCH] Add `is_series` type guard, with tests --- hyperglass/types.py | 2 +- hyperglass/util/tests/test_typing.py | 13 ++++++++++++- hyperglass/util/typing.py | 7 +++++++ 3 files changed, 20 insertions(+), 2 deletions(-) diff --git a/hyperglass/types.py b/hyperglass/types.py index ef2e0d5..6bfd9ca 100644 --- a/hyperglass/types.py +++ b/hyperglass/types.py @@ -6,4 +6,4 @@ import typing as _t _S = _t.TypeVar("_S") Series = _t.Union[_t.MutableSequence[_S], _t.Tuple[_S], _t.Set[_S]] -"""Like Sequence, but excludes `str`.""" +"""Like `typing.Sequence`, but excludes `str`.""" diff --git a/hyperglass/util/tests/test_typing.py b/hyperglass/util/tests/test_typing.py index a5ed2c9..66fe8ca 100644 --- a/hyperglass/util/tests/test_typing.py +++ b/hyperglass/util/tests/test_typing.py @@ -5,7 +5,7 @@ import typing # Local -from ..typing import is_type +from ..typing import is_type, is_series class EmptyTestClass: @@ -64,3 +64,14 @@ def test_is_type(): result = is_type(value, _type) if result is not expected: raise AssertionError(f"Got `{value}`, expected `{str(_type)}`") + + +def test_is_series(): + checks = ( + ((1, 2, 3), True), + ([1, 2, 3], True), + ("1,2,3", False), + ({1, 2, 3}, True), + ) + for value, expected in checks: + assert is_series(value) is expected diff --git a/hyperglass/util/typing.py b/hyperglass/util/typing.py index 760b2fa..c9cefbc 100644 --- a/hyperglass/util/typing.py +++ b/hyperglass/util/typing.py @@ -25,3 +25,10 @@ def is_type(value: typing.Any, *types: typing.Any) -> bool: return isinstance(value, type(_type)) return isinstance(value, origin) return False + + +def is_series(value: typing.Any) -> bool: + """Determine if a value is a `hyperglass.types.Series`, i.e. non-string `typing.Sequence`.""" + if isinstance(value, (typing.MutableSequence, typing.Tuple, typing.Set)): + return True + return False