Core

This page documents the functions available to perform argument checking.

These can be used with checker-likes (types or tuples of types) or with checkers from the other sections to check for more complex conditions.

Also present is the documentation of the One checker.

argscheck.core.check(checker_like, value, name='', raise_on_error=True)

Check an argument (and possibly convert it).

The default behaviour is:

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

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

Parameters
  • checker_likeCheckerLike – Describes the check performed on value.

  • valueAny - The value of the argument being checked.

  • nameOptional[str] - Optional name of the argument being checked. Will be used in error messages.

  • raise_on_errorbool - Whether to use the default or the alternative behaviour of this function.

Example

from argscheck import check


check(int, 1)      # Passes, 1 is returned.
check(int, 'one')  # Fails, a TypeError is raised.

Users who prefer to handle the check failure on their own, can use the alternative behaviour by passing raise_on_error=False.

In this case, exceptions are never raised and the return value is (passed, new_value, old_value):

  • passed - is a boolean indicating whether the check passed or not.

  • new_value - If passed, this is the checked (and possibly converted) argument value. Otherwise, this is the exception that would have been raised by the default behaviour.

  • old_value - is the same object value passed to check().

Example

from argscheck import check


passed, value, _ = check(int, 1, raise_on_error=False)      # passed is True, value is 1.
passed, value, _ = check(int, 'one', raise_on_error=False)  # passed is False, value is a TypeError.
argscheck.core.check_args(function=None, raise_on_error=True)

A decorator that makes a function (or a method) automatically perform argument checking each time its called.

The checker used on each parameter is extracted from its annotation in the function definition statement (parameters without annotation will not be checked).

Example

from argscheck import check_args, Number, Float


@check_args
def convex_sum(a: Number, b: Number, alpha: (0.0 <= Float) <= 1.0):
    return alpha * a + (1.0 - alpha) * b


convex_sum(0, 2, 0.0)    # Passes, 2.0 is returned
convex_sum(0, 2, 1.1)    # Fails, a ValueError is raised (1.1 is greater than 1.0)
convex_sum(0, [2], 0.5)  # Fails, a TypeError is raised ([2] is not a number)

Just like with check(), we may prefer to handle errors ourselves, in which case we can use the alternative behaviour by passing a flag to the decorator.

Example

import logging
from argscheck import check_args, Number, Float


@check_args(raise_on_error=False)
def convex_sum(a: Number, b: Number, alpha: (0.0 <= Float) <= 1.0):
    # Check a
    passed, exception, a = a
    if not passed:
        logging.critical('Error in a=%s argument of convex_sum: %s', a, exception)
        raise exception

    # Check b
    passed, exception, b = b
    if not passed:
        logging.critical('Error in b=%s argument of convex_sum: %s', b, exception)
        raise exception

    # Check alpha
    passed, exception, alpha = alpha
    if not passed:
        logging.critical('Error in alpha=%s argument of convex_sum: %s', alpha, exception)
        raise exception

    return alpha * a + (1.0 - alpha) * b


convex_sum(0, 2, 0.0)    # Passes, 2.0 is returned
convex_sum(0, 2, 1.1)    # Fails, a ValueError is raised (1.1 is greater than 1.0)
convex_sum(0, [2], 0.5)  # Fails, a TypeError is raised ([2] is not a number)
argscheck.core.validator(checker, name, raise_on_error=True, **kwargs)

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

Parameters
  • checkerCheckerLike - Describes the check that will be performed on the field.

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

  • raise_on_errorbool – See check().

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

Example

from typing import Any

from pydantic import BaseModel
from argscheck import validator, Optional


class UserModel(BaseModel):
    items: Any
    check_items = validator(Optional(dict, default_factory=dict), 'items')


UserModel(items={'a': 1, 'b': 2}).items  # Passes, {'a': 1, 'b': 2} is returned
UserModel(items=None).items              # Passes, {} is returned
UserModel(items=[1, 2]).items            # Fails, a TypeError is raised
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 check, One


check(One(list, tuple), [])  # Passes, [] is returned
check(One(list, tuple), {})  # Fails, a TypeError is raised

# Can also be used with a shorthand initialization
check((list, tuple), [])  # Passes, [] is returned