xoutil.connote – Predicates

A predicate is seen as a property that a subject has or is characterized by. A predicate is therefore an expression that can be true of something (involve as a necessary condition of consequence). Thus, the expression “is moving” is true of those things that are moving.

The main class of this module is Predicate.

New in version 1.7.0.

class xoutil.connote.Predicate(*args, **kwargs)[source]

A definition of a validation function using a grammar of simple predicates.

All parameters are checkers; those given by name (keyword arguments) are used to produce named anonymous checkers, for example:

>>> from xoutil.predicate import Predicate
>>> p = Predicate(int, is_valid_age=lambda age: 0 < age <= 120)

A lambda wrapper (lw()) can be used to decorate anonymous functions; so, last declaration is equivalent to:

>>> p = Predicate(int, lw('is_valid_age', lambda age: 0 < age <= 120))

There is a special keyword argument (‘__named__’); if present and True; a name will be generated for the predicate.

Each checker could be:

  • A type (or tuple of types) to test with isinstance(value, checker)
  • A set, a value will be valid if is contained in the set.
  • A mapping, a value will be valid if is contained in the mapping and its value is True.
  • A tuple of other inner checkers, if any of the checkers validates a value, the value is valid (OR).
  • A list of other inner checkers, all checkers must validate the value (AND).
  • A callable that receives the value and returns True if the value is valid.
  • True, False or any instance of Logical could be used as checkers always validating or invalidating the value.
  • An empty list is synonym of True, an empty tuple, set or mapping is synonym of False.

Any other value will return False (fail).

Note

Above definition is controversial, maybe a exception must be raised if a invalid checker is used.

With this class, it could be built real type checkers, for example:

>>> from xoutil.predicate import Predicate as pp
>>> numbers = (int, float)
>>> is_valid_age = pp(numbers, valid_age=lambda age: 0 < age <= 120)
>>> is_valid_age(100)
True

>>> is_valid_age(130)
False

>>> is_valid_age(85.5)
True

Other simple example:

>>> always_true = predicate(True)
>>> always_true(False)
True

>>> always_false = predicate(False)
>>> always_false(True)
False

>>> always_true = predicate()
>>> always_true(1)
True

>>> always_true('any string')
True

>>> always_false = predicate(())
>>> always_false(1)
False

>>> always_false('any string')
False
get_name()[source]

Get a name representation suitable for this predicate.

This method is used in the constructor to cache this value if keyword argument ‘__named__’ is given and True.