Verification (pytyp.spec.check)

This module provides routines to verify type specifications.

A value is verified in one of four ways:

  1. If the value is a subclass of the specification.
  2. If the value’s class is registered with the specification (using the register() method).
  3. If the value is registered with the specification (using the register_instance() method).
  4. If the value is a container that can be iterated over and whose contents can be verified.

The last of these must inspect all values, so can be inefficient.

Hint

Don’t forget that type specifications also work with isinstance() and issubclass().

Checked

pytyp.spec.check.checked(func)[source]

A decorator that adds runtime verification of type annotations to a function or method.

>>> @checked
... def str_len(s:str) -> int:
...     return len(s)
>>> str_len('abc')
3
>>> str_len([1,2,3])
Traceback (most recent call last):
  ...
TypeError: Type str inconsistent with [1, 2, 3].
>>> @checked
... def bad_len(s:str) -> int:
...     return 'wrong'
>>> bad_len('abc')
Traceback (most recent call last):
  ...
TypeError: Type int inconsistent with 'wrong'.

Verify

pytyp.spec.check.verify(value, spec)[source]

If value is not an instance of spec then raise a TypeError.

Table Of Contents

Previous topic

YAML Serialisation (pytyp.s11n.yaml)

Next topic

Dynamic Dispatch by Type

This Page