Skip to content

Commit

Permalink
Function to check if all elements are of the same type (#1)
Browse files Browse the repository at this point in the history
Add tests, include example in README
  • Loading branch information
jkanche authored Oct 11, 2023
1 parent ccbafbd commit 0b1e506
Show file tree
Hide file tree
Showing 4 changed files with 62 additions and 0 deletions.
13 changes: 13 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -68,3 +68,16 @@ y = np.array([10, 20, 30, 40, 50])
biocutils.subset(y, [0, 2, 4])
## array([10, 30, 50])
```

### `is_list_of_type`

Checks if all elements of a list or tuple are of the same type.

```python
import biocutils
import numpy as np

x = [np.random.rand(3), np.random.rand(3, 2)]
biocutils.is_list_of_type(x, np.ndarray)
## True
```
1 change: 1 addition & 0 deletions src/biocutils/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,3 +21,4 @@
from .intersect import intersect
from .union import union
from .subset import subset
from .is_list_of_type import is_list_of_type
21 changes: 21 additions & 0 deletions src/biocutils/is_list_of_type.py
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
)
27 changes: 27 additions & 0 deletions tests/test_utils.py
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)

0 comments on commit 0b1e506

Please sign in to comment.