Collections¶
This module contains checkers for collection objects.
In this context, a collection is a class that:
Has
__len__()implemented.Its instances are iterable.
Can be instantiated from an iterable.
Collections can be homogeneous, i.e. all items in it have some shared properties. Homogeneity can be checked using the
*args parameter.
- class argscheck.collection.Collection(*args, **kwargs)¶
Check if
xis a collection.- Parameters
args – Optional[Tuple[CheckerLike]] – If provided, this check will be applied 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 Collection # Check if a non empty collection of floats checker = Collection(float, len_gt=0) checker.check({1.2, 3.4}) # Passes, returns {1.2, 3.4} checker.check([1.1, 2.2, 3.3]) # Passes, returns [1.1, 2.2, 3.3] checker.check(()) # Fails, raises ValueError (empty collection) checker.check('abcd') # Fails, raises TypeError (collection of str and not float)
- class argscheck.collection.Set(*args, **kwargs)¶
Check if
xis a homogenoussetand optionally, check its length and compare it to other sets using binary operators, e.g. usinggt=otherwill check ifxis a superset ofother(which must also be aset).- Parameters
args – Optional[Tuple[CheckerLike]] – If provided, this check will be applied 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 Set # Check if a set of length at least 2 and is a superset of {'a'} checker = Set(gt={'a'}, len_ge=2) checker.check({'a', 'b'}) # Passes, returns {'a', 'b'} checker.check({'a', 1, ()}) # Passes, returns {'a', 1, ()} checker.check(['a', 'b']) # Fails, raises TypeError (type is list and not set) checker.check({'a'}) # Fails, raises ValueError (length is 1 and not 2 or greater) checker.check({'b', 'c'}) # Fails, raises ValueError ({'b', 'c'} is not a superset of {'a'})