Validation (isa & issubclass)
This module provides type validation functions for Python with support for the typing
module.
It uses the same internal mechanism as used by ‘dataclass’ and ‘dispatch’ in order to resolve and validate types and values.
You may use them to replace isinstance()
and issubclass
. See benchmarks.
Functions
- runtype.validation.isa(obj, t)
Tests if ‘obj’ is of type ‘t’
Behaves like Python’s isinstance, but supports the
typing
module and constraints.
- runtype.validation.ensure_isa(obj, t, sampler=None)
Ensure ‘obj’ is of type ‘t’. Otherwise, throws a TypeError
- runtype.validation.assert_isa(obj, t)
Ensure ‘obj’ is of type ‘t’. Otherwise, throws a TypeError
Does nothing if Python is run with -O. (like the assert statement)
- runtype.validation.issubclass(t1, t2)
Test if t1 is a subclass of t2
- Parameters:
type (t1 - a) –
types (t2 - a type or a tuple of) –
Behaves like Python’s issubclass, but supports the
typing
module.
- runtype.validation.is_subtype(t1, t2)
Test if t1 is a subtype of t2
Element-wise validation
When called on generics such as List, Tuple, Set and Dict, runtype will iterate over each element and call ensure_isa() recursively.
Example:
>>> isa([1,2], List[int])
True
>>> isa([1,"a"], List[int])
False
>>> isa([{1: 2}], List[Dict[int, int]])
True
>>> isa([{1: 2}], List[Dict[int, str]])
False
How does it work?
Runtype maps the given types onto an internal type system, that is capable of expressing the Python type system.
In order to validate a value against a type, we do the following:
Convert (cast) the given type into an instance of PythonType, that represents the given type within the internal type system. This operation is cached.
Call the PythonType.validate_instance() method with the given value. Each subclass has its own implementation. For example:
In PythonDataType (e.g. Int or DateTime), the method will simply call Python’s isinstance() on the value.
In SequenceType (e.g. List or Iter), after isinstance(), this method will call itself recursively for each item.
The internal type system is implemented using the Type Classes module.