Iterator and Iterable

This module contains checkers for iterator and iterable arguments.

In this context, an iterator is a class that has __next__() implemented, so each call to next() produces an item, until finally StopIteration is raised.

An iterable is a class that has __iter__() implemented, so it can be iterated over by a for loop or by explicitly creating an iterator with iter() and repeatedly calling next() on the resulting iterator.

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

Check if x is a homogeneous iterator, i.e. each item satisfies the same set of checkers.

The usage of the Iterator checker is a little different than the rest: calling check(x) returns a wrapper around x, and calling next() on it will call next() on x and check each item before it is returned.

Parameters

argsTuple[CheckerLike] – Describes what each item from the iterator must be.

Example

from argscheck import Iterator

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

next(iterator)  # Passes, returns 'a'
next(iterator)  # Passes, returns True
next(iterator)  # Fails, raises TypeError (1.1 is not an str or bool).
check(*args, **kwargs)

Check an argument (and possibly convert it, depending on the particular checker instance).

A call to check() will have one of two possible outcomes:

  1. Check passes, the checked (and possibly converted) argument will be returned.

  2. Check fails, an appropriate exception with an error message will be raised.

Also, there are two possible calling signatures:

checker.check(value)
checker.check(name=value)

The only difference is that in the second call, name will appear in the error message in case the check fails.

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

Same as Iterator, plus, x can be a plain iterable (not necessarily an iterator).

Example

from argscheck import Iterable

# Each item must be an str or bool instance
checker = Iterable(str, bool)

# Can be iterated over with a for loop
for item in checker.check(['a', True, 1.1]):
    print(item)     # prints "a\n", "True\n", then raises TypeError (1.1 is not an str or bool).

# Can be iterated over manually
iterator = iter(checker.check(['a', True, 1.1]))
next(iterator)  # Passes, returns 'a'
next(iterator)  # Passes, returns True
next(iterator)  # Fails, raises TypeError (1.1 is not an str or bool).