always_iterable

iteration_utilities.always_iterable(obj, excluded_types=None, empty_if_none=False)

Make the obj iterable.

New in version 0.11.0.

Parameters:
objany type

The object to make iterable.

excluded_typestype or tuple of types, optional

The types that should not be interpreted as already-iterable. If the argument is omitted, then str and bytes (but not subclasses) will be wrapped. If None, then no type is excluded.

empty_if_nonebool, optional

If this argument is True, then an empty iterable will be returned if obj is None. Default is False.

Returns:
iterableany type

An iterable over obj if it was considered iterable, otherwise an iterable that will only yield one item the obj.

Examples

In case the obj is iterable an iterator over the object is returned:

>>> from iteration_utilities import always_iterable
>>> list(always_iterable([1, 2, 3]))
[1, 2, 3]

If it wasn’t iterable or it was excluded explicitly an iterator is returned which yields one item, the obj:

>>> list(always_iterable(1))
[1]
>>> list(always_iterable([1, 2, 3], excluded_types=list))
[[1, 2, 3]]

By default strings are considered not iterable, but this can be overridden using None as excluded_types:

>>> list(always_iterable('abc'))
['abc']
>>> list(always_iterable('abc', excluded_types=None))
['a', 'b', 'c']

If an empty iterator should be returned if obj is None, then empty_if_none can be used:

>>> list(always_iterable(None))
[None]
>>> list(always_iterable(None, empty_if_none=True))
[]