Collections

This module contains checkers for collection objects.

In this context, a collection is a class that:

  1. Has __len__() implemented.

  2. Its instances are iterable.

  3. 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 x is a collection.

Parameters
  • argsOptional[Tuple[CheckerLike]] – If provided, this check will be applied 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 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 x is a homogenous set and optionally, check its length and compare it to other sets using binary operators, e.g. using gt=other will check if x is a superset of other (which must also be a set).

Parameters
  • argsOptional[Tuple[CheckerLike]] – If provided, this check will be applied 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 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'})