Core

This module contains the Checker base class, the check_args() function decorator, as well as other basic checkers that do not correspond to a particular type or protocol.

argscheck.core.check_args(fn)

A decorator, that when applied to a function:

  1. Gathers checkers from parameter annotations in function’s signature.

  2. Performs argument checking (and possibly conversion) on each function call.

Example

from argscheck import check_args, Number, Float

# Check if a, b are numbers and alpha is a float in range [0,1]
@check_args
def convex_sum(a: Number, b: Number, alpha: Float(ge=0.0, le=1.0)):
    return alpha * a + (1.0 - alpha) * b

convex_sum(0, 2, 0.0)    # Passes, returns 2.0
convex_sum(0, 2, 1.1)    # Fails, raises ValueError (1.1 is greater than 1.0)
convex_sum(0, [2], 0.5)  # Fails, raises TypeError ([2] is not a number)
class argscheck.core.Checker

Base class for all checkers. This is presented mainly for the user-facing methods described below.

check(*args, **kwargs)

Check an argument (and possibly convert it, depending on the particular checker instance).

A call to check() will have one of two possible outcomes:

  1. Check passes, the checked (and possibly converted) argument will be returned.

  2. Check fails, an appropriate exception with an error message will be raised.

Also, there are two possible calling signatures:

checker.check(value)
checker.check(name=value)

The only difference is that in the second call, name will appear in the error message in case the check fails.

validator(name, **kwargs)

Create a validator for a field in a pydantic model. The validator will perform the checking and conversion by calling the Checker.check() method.

Parameters
  • namestr – Name of field for which validator is created.

  • kwargsOptional – Passed to pydantic.validator as-is.

class argscheck.core.Typed(*args, **kwargs)

Check if x is an instance of a given type (or types) using isinstance(x, args).

Parameters

argsTuple[Type] – One or more types.

Example

from argscheck import Typed

# Check if integer or float
checker = Typed(int, float)

checker.check(1.234)    # Passes, returns 1.234
checker.check("1.234")  # Fails, raises TypeError (type is str and not int or float)
class argscheck.core.Optional(*args, default_value=<MISSING>, default_factory=<MISSING>, sentinel=None, **kwargs)

Check if x is None or something else, similarly to typing.Optional.

Parameters
  • argsTuple[CheckerLike] – Specifies what x may be (other than None).

  • default_valueOptional[Any] – If x is None, it will be replaced by default_value.

  • default_factoryOptional[Callable] – if x is None, it will be replaced by a value freshly returned from default_factory(). This is useful for setting default values that are of mutable types.

  • sentinelOptional[Any]x is sentinel will be used to determine if the x is missing, instead of x is None.

Example

from argscheck import Optional

# Check if a list, set or None, replace None with a fresh list
checker = Optional(list, set, default_factory=list)

checker.check([1, 2, 3])  # Passes, returns [1, 2, 3]
checker.check({1, 2, 3})  # Passes, returns {1, 2, 3}
checker.check(None)       # Passes, returns []
checker.check("string")   # Fails, raises TypeError ("string" is neither None nor a list or a set)
class argscheck.core.Comparable(*args, lt=None, le=None, ne=None, eq=None, ge=None, gt=None, other_type=<class 'object'>, **kwargs)

Check if x correctly compares to other value(s) using any of the following binary operators: <, <=, !=, ==, >= or >.

Comparison need not necessarily be between numeric types, as can be seen in the example below.

Parameters
  • 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.

  • other_typeOptional[Union[Type, Tuple[Type]]] – If provided, restricts the types to which x can be compared, e.g. other_type=int with ne=1.0 will raise a TypeError (because 1.0 is not an int).

Example

from argscheck import Comparable

# Check if a strict subset
checker = Comparable(lt={'a', 'b'})

checker.check(set())       # Passes, returns set()
checker.check({'a'})       # Passes, returns {'a'}
checker.check({'a', 'b'})  # Fails, raises ValueError ({'a', 'b'} is equal to {'a', 'b'})
checker.check('a')         # Fails, raises TypeError (< is not supported between set and str)
class argscheck.core.One(*args, **kwargs)

Check if x matches exactly one of a set of checkers.

Parameters

argsTuple[CheckerLike] – At least two checker-like object(s) out of which exactly one must pass.

Example

from argscheck import One

checker = One()