Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix is list on Numpy's masked arrays #25

Merged
merged 1 commit into from
Jan 15, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 12 additions & 5 deletions src/biocutils/is_list_of_type.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
from typing import Callable, Union

import numpy as np
import numpy.ma as ma

__author__ = "jkanche"
__copyright__ = "jkanche"
__license__ = "MIT"


def is_list_of_type(
x: Union[list, tuple], target_type: Callable, ignore_none: bool = False
) -> 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:
Expand All @@ -19,10 +20,16 @@ def is_list_of_type(

Returns:
True if ``x`` is a list or tuple and all elements are of the target
type (or None, if ``ignore_none = True``). Otherwise, false.
type (or None, if ``ignore_none = True``). Otherwise, False.
"""
if not isinstance(x, (list, tuple)):
if not isinstance(x, (list, tuple, np.ndarray, ma.MaskedArray)):
return False

if isinstance(x, ma.MaskedArray):
if not ignore_none:
return all(x.mask) and all(isinstance(item, target_type) for item in x.data)
else:
return all(isinstance(item, target_type) for item in x.data[x.mask])

if not ignore_none:
return all(isinstance(item, target_type) for item in x)
Expand Down
11 changes: 11 additions & 0 deletions tests/test_list_type_checks.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import numpy as np
import numpy.ma as ma
import pytest
from biocutils import is_list_of_type

Expand Down Expand Up @@ -29,3 +30,13 @@ def test_numpy_elems():
x = [np.random.rand(3), np.random.rand(3, 2)]

assert is_list_of_type(x, np.ndarray)

def test_numpy_arrays():
x = np.random.rand(3)

assert is_list_of_type(x, float)

x = ma.array([1, None, 3], mask = [0, 1, 0], dtype=np.float32)

assert is_list_of_type(x, np.float32, ignore_none=True)
assert is_list_of_type(x, np.float32) is False
Loading