Collections¶
This page documents checkers for collection objects.
We define a collection as a class that:
Implements __len__().
Its instances are iterable.
Can be instantiated from an iterable.
Collections can be homogeneous, i.e. all items in it satisfy the same set of conditions.
Homogeneity can be checked for using by providing one or more positional arguments to the checker’s constructor.
- class argscheck.collection.Collection(*args, **kwargs)¶
Check if x is a (possible homogeneous) collection.
- Parameters
args – Optional[Tuple[CheckerLike]] – If provided, apply the given check to each item in x.
len_lt – Optional[int] – Check if len(x) < len_lt.
len_le – Optional[int] – Check if len(x) <= len_le.
len_ne – Optional[int] – Check if len(x) != len_ne.
len_eq – Optional[int] – Check if len(x) == len_eq.
len_ge – Optional[int] – Check if len(x) >= len_ge.
len_gt – Optional[int] – Check if len(x) > len_gt.
- Example
from argscheck import check, Collection # Check if a non-empty collection of floats checker = Collection(float, len_gt=0) check(checker, {1.2, 3.4}) # Passes, {1.2, 3.4} is returned check(checker, [1.1, 2.2, 3.3]) # Passes, [1.1, 2.2, 3.3] is returned check(checker, ()) # Fails, a ValueError is raised (empty collection) check(checker, 'abcd') # Fails, a TypeError is raised (collection of str and not float)
- class argscheck.collection.Set(*args, **kwargs)¶
Check if x is a (possibly homogenous) set and optionally, check its length.
x can also be compared to other sets using binary comparison operators, e.g. using gt=other will check if x is a superset of other (which must also be a set).
Comparison shorthands can be used here, see example.
- Parameters
args – Optional[Tuple[CheckerLike]] – If provided, apply the given check to each item in x.
lt – Optional[Any] – Check if x < lt.
le – Optional[Any] – Check if x <= le.
ne – Optional[Any] – Check if x != ne.
eq – Optional[Any] – Check if x == eq.
ge – Optional[Any] – Check if x >= ge.
gt – Optional[Any] – Check if x > gt.
len_lt – Optional[int] – Check if len(x) < len_lt.
len_le – Optional[int] – Check if len(x) <= len_le.
len_ne – Optional[int] – Check if len(x) != len_ne.
len_eq – Optional[int] – Check if len(x) == len_eq.
len_ge – Optional[int] – Check if len(x) >= len_ge.
len_gt – Optional[int] – Check if len(x) > len_gt.
- Example
from argscheck import check, Set # Check if a set of length at least 2 and is a superset of {'a'} checker = Set(len_ge=2) > {'a'} check(checker, {'a', 'b'}) # Passes, {'a', 'b'} is returned check(checker, {'a', 1, ()}) # Passes, {'a', 1, ()} is returned check(checker, ['a', 'b']) # Fails, a TypeError is raised (type is list and not set) check(checker, {'a'}) # Fails, a ValueError is raised (length is 1 and not 2 or greater) check(checker, {'b', 'c'}) # Fails, a ValueError is raised ({'b', 'c'} is not a superset of {'a'})