-
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.
Optionally ignore Nones when checking the type of list contents.
- Loading branch information
Showing
2 changed files
with
20 additions
and
9 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
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) |
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