Iterator and Iterable

This page documents checkers for iterators and iterable objects.

We define and iterator as a class that:

  1. Implements __next__().

  2. Each call to next() on iterator instances returns some value, until finally StopIteration is raised.

We define an iterable as a class that:

  1. Implements __iter__().

  2. Calling iter() on iterable instances returns an iterator.

Iterators and iterables can be homogeneous, i.e. all items they yield satisfy the same set of conditions.

Homogeneity can be checked for by providing one or more positional arguments to the checker’s constructor.

The usage of the Iterator and Iterable checkers, does not follow the usual pattern of:

checker = SomeChecker()
check(checker, good_value)  # Passes, the good value is returned
check(checker, bad_value)  # Fails, an exception is raised

Instead, calling check() returns a wrapper around the (iterator or iterable) value, and checking is preformed as the values are being produced by the iterator or iterable.

See examples for Iterator and Iterable.

Warning

Composing Iterator, Iterable inside other checkers has limited support (only Optional is supported).

e.g. Collection(Iterable(int)) is not supported (but Iterable(Collection(int)) is supported).

class argscheck.iter.Iterator(*args, **kwargs)

Check if x is a (possible homogeneous) iterator.

Parameters

argsOptional[Tuple[CheckerLike]] – If provided, apply the given check to each item from x.

Example

from argscheck import check, Iterator


# Each item must be an str or bool instance
iterator = check(Iterator(str, bool), iter(['a', True, 1.1]))

next(iterator)  # Passes, 'a' is returned
next(iterator)  # Passes, True is returned
next(iterator)  # Fails, a TypeError is raised (1.1 is not an str or bool).
class argscheck.iter.Iterable(*args, **kwargs)

Check if x is a (possible homogeneous) iterable.

Parameters

argsOptional[Tuple[CheckerLike]] – If provided, apply the given check to each item from x.

Example

from argscheck import check, Iterable


# Each item must be an str or bool instance
for item in check(Iterable(str, bool), ['a', True, 1.1]):
    print(item)     # prints "a\n", "True\n", then raises TypeError (1.1 is not an str or bool).