is_iterable

Contents

is_iterable#

is_iterable(obj: Any, str_allowed: bool = False)[source]#

Is the object an iterable?

Useful to replace this kind of code:

>>> if isinstance(my_items, (list, tuple)):
>>>     do...

by:

>>> if is_iterable(my_items):
>>>     do...

It allows not to forget checking for some iterables you aren’t aware of.

Parameters:
  • obj (Any) – Object to check

  • str_allowed (bool) – If set, strings are considered as iterable. If not, they are not considered as iterable.

Returns:

True if the iobject is iterable

Return type:

bool

Examples

>>> is_iterable((1, 2, 3))
True
>>> is_iterable([1, 2, 3])
True
>>> is_iterable({1, 2, 3})
True
>>> is_iterable(np.array([1, 2, 3]))
True
>>> is_iterable("1, 2, 3")
False
>>> is_iterable("1, 2, 3", str_allowed=True)
True
>>> is_iterable(1)
False
>>> is_iterable(AnyPath("1, 2, 3"))
False