make_iterable

Contents

make_iterable#

make_iterable(obj: Any, str_allowed: bool = False, convert_none: bool = False) list[source]#

Convert the object to a list if this object is not iterable

Useful to replace this kind of code:

>>> if to_convert is not None and not isinstance(to_convert, (list, tuple)):
>>>    to_convert = [to_convert]

by:

>>> to_convert = make_iterable(to_convert)

or:

>>> if isinstance(my_items, (list, tuple)):
>>>    first_item = my_items[0]
>>> else:
>>>    first_item = my_items

by:

>>> first_item = make_iterable(to_convert)[0]
Parameters:
  • obj (Any) – Object to check

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

  • convert_none (bool) – If true, if obj is None, then it won’t be converted into a list. By default, Nones are not converted to list.

Returns:

Object as an iterable

Return type:

list

Examples

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