-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Function to check if all elements are of the same type (#1)
Add tests, include example in README
- Loading branch information
Showing
4 changed files
with
62 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,21 @@ | ||
from typing import Any | ||
|
||
__author__ = "jkanche" | ||
__copyright__ = "jkanche" | ||
__license__ = "MIT" | ||
|
||
|
||
def is_list_of_type(x: Any, target_type) -> 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``. | ||
Returns: | ||
bool: True if ``x`` is :py:class:`list` or :py:class:`tuple` and | ||
all elements are of the same type. | ||
""" | ||
return isinstance(x, (list, tuple)) and all( | ||
isinstance(item, target_type) for item in x | ||
) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,27 @@ | ||
import numpy as np | ||
import pytest | ||
from biocutils import is_list_of_type | ||
|
||
|
||
def test_simple_list(): | ||
x = [1, 2, 3] | ||
|
||
assert is_list_of_type(x, int) | ||
|
||
y = [1.2, 2.3, 4.5] | ||
assert is_list_of_type(y, float) | ||
|
||
xt = (1, 2, 3) | ||
assert is_list_of_type(xt, int) | ||
|
||
|
||
def test_should_fail(): | ||
x = [1, [2, 3, 4], 6] | ||
|
||
assert is_list_of_type(x, int) is False | ||
|
||
|
||
def test_numpy_elems(): | ||
x = [np.random.rand(3), np.random.rand(3, 2)] | ||
|
||
assert is_list_of_type(x, np.ndarray) |