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

Function to check if all contains elements are of the same type #1

Merged
merged 4 commits into from
Oct 11, 2023
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
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)