annotation.functions - Coerce and validate parameters

When the drytools.annotation.composition.compose_annotations() decorator is used, these functions can he used as annotations to coerce and/or validate parameters.

check(predicate, *args, raises=<class 'ValueError'>, **kwargs)[source]

Factory for univariate validation functions

Parameters:
  • predicate (callable) – Function returning True if the input value is valid, False otherwise. The value to be checked is used as the first argument. Additional (constant) arguments can be supplied in args and kwargs (see example).
  • raises (callable) – Constructor for Exception to raise if predicate returns False
  • kwargs (args,) – additional arguments for predicate
Returns:

Identity function (ie: returns the value passed to it) except that it raises exception_type if predicate returns False when applied to its input value.

Return type:

func

Example

>>> from operator import gt
>>> check_positive = check(gt, 0)
>>> check_positive(5)
5
>>> check_positive(-3)
Traceback (most recent call last):
    ...
ValueError: -3
iterify(x, excluded_types=<class 'str'>)[source]

Coerce to an iterable

Parameters:
  • x – Object to coerce
  • excluded_types (type or iterable) – one or more types to treat as elements even if they are iterable
Returns:

Either x (if it’s iterable and not one of excluded_types) or a single-element list containing x

Return type:

iterable

Example

>>> list(iterify('foo'))
['foo']
>>> list(iterify('foo', excluded_types={}))
['f', 'o', 'o']
>>> iterify(['foo', 'bar', 'baz'])
['foo', 'bar', 'baz']