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
xis a homogeneous iterator, i.e. each item satisfies the same set of checkers.The usage of the
Iteratorchecker is a little different than the rest: callingcheck(x)returns a wrapper aroundx, and callingnext()on it will callnext()onxand check each item before it is returned.- Parameters
args – Tuple[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:Check passes, the checked (and possibly converted) argument will be returned.
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,
namewill appear in the error message in case the check fails.
- class argscheck.iter.Iterable(*args, **kwargs)¶
Same as
Iterator, plus,xcan 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).