Collections

This page documents checkers for collection objects.

We define a collection as a class that:

  1. Implements __len__().

  2. Its instances are iterable.

  3. 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
  • argsOptional[Tuple[CheckerLike]] – If provided, apply the given check to each item in x.

  • len_ltOptional[int] – Check if len(x) < len_lt.

  • len_leOptional[int] – Check if len(x) <= len_le.

  • len_neOptional[int] – Check if len(x) != len_ne.

  • len_eqOptional[int] – Check if len(x) == len_eq.

  • len_geOptional[int] – Check if len(x) >= len_ge.

  • len_gtOptional[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
  • argsOptional[Tuple[CheckerLike]] – If provided, apply the given check to each item in x.

  • ltOptional[Any] – Check if x < lt.

  • leOptional[Any] – Check if x <= le.

  • neOptional[Any] – Check if x != ne.

  • eqOptional[Any] – Check if x == eq.

  • geOptional[Any] – Check if x >= ge.

  • gtOptional[Any] – Check if x > gt.

  • len_ltOptional[int] – Check if len(x) < len_lt.

  • len_leOptional[int] – Check if len(x) <= len_le.

  • len_neOptional[int] – Check if len(x) != len_ne.

  • len_eqOptional[int] – Check if len(x) == len_eq.

  • len_geOptional[int] – Check if len(x) >= len_ge.

  • len_gtOptional[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'})