From 62765118e62929526886dd634436b44559a7af2e Mon Sep 17 00:00:00 2001 From: LTLA Date: Tue, 24 Oct 2023 15:22:48 -0700 Subject: [PATCH] Optionally ignore Nones when checking the type of list contents. --- src/biocutils/is_list_of_type.py | 25 ++++++++++++++++--------- tests/test_list_type_checks.py | 4 ++++ 2 files changed, 20 insertions(+), 9 deletions(-) diff --git a/src/biocutils/is_list_of_type.py b/src/biocutils/is_list_of_type.py index 6cf1968..d422f16 100644 --- a/src/biocutils/is_list_of_type.py +++ b/src/biocutils/is_list_of_type.py @@ -1,21 +1,28 @@ -from typing import Any +from typing import Any, Callable, Union __author__ = "jkanche" __copyright__ = "jkanche" __license__ = "MIT" -def is_list_of_type(x: Any, target_type) -> bool: +def is_list_of_type(x: Union[list, tuple], target_type: Callable, ignore_none: bool = False) -> bool: """Checks if ``x`` is a list, and whether all elements of the list are of the same type. Args: - x (Any): Any list-like object. - target_type (callable): Type to check for, e.g. ``str``, ``int``. + x: A list or tuple of values. + + target_type: Type to check for, e.g. ``str``, ``int``. + + ignore_none: Whether to ignore Nones when comparing to ``target_type``. Returns: - bool: True if ``x`` is :py:class:`list` or :py:class:`tuple` and - all elements are of the same type. + True if ``x`` is a list or tuple and all elements are of the target + type (or None, if ``ignore_none = True``). Otherwise, false. """ - return isinstance(x, (list, tuple)) and all( - isinstance(item, target_type) for item in x - ) + if not isinstance(x, (list, tuple)): + return False + + if not ignore_none: + return all(isinstance(item, target_type) for item in x) + + return all((isinstance(item, target_type) or item is None) for item in x) diff --git a/tests/test_list_type_checks.py b/tests/test_list_type_checks.py index 434ff6b..78a8f6a 100644 --- a/tests/test_list_type_checks.py +++ b/tests/test_list_type_checks.py @@ -14,6 +14,10 @@ def test_simple_list(): xt = (1, 2, 3) assert is_list_of_type(xt, int) + xt = (1, 2, None) + assert not is_list_of_type(xt, int) + assert is_list_of_type(xt, int, ignore_none = True) + def test_should_fail(): x = [1, [2, 3, 4], 6]