Skip to content

Commit

Permalink
Optionally ignore Nones when checking the type of list contents.
Browse files Browse the repository at this point in the history
  • Loading branch information
LTLA committed Oct 24, 2023
1 parent 1fba252 commit 6276511
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 9 deletions.
25 changes: 16 additions & 9 deletions src/biocutils/is_list_of_type.py
Original file line number Diff line number Diff line change
@@ -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)
4 changes: 4 additions & 0 deletions tests/test_list_type_checks.py
Original file line number Diff line number Diff line change
Expand Up @@ -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]
Expand Down

0 comments on commit 6276511

Please sign in to comment.