Defining Custom Types¶
Special constraints can be imposed with this handy decorater.
datatyping.customtype¶
-
datatyping.
customtype
(check_function)¶ Decorate a function, so it can be used for type checking.
Example
>>> @customtype ... def two_item_list(lst): ... if len(lst) != 2: ... raise TypeError('length %d!!!' % len(lst)) ... >>> validate([two_item_list], [[1, 2], [3, 4]]) >>> validate([two_item_list], [[1, 2], [3, 4, 5]]) TypeError: length 3!!!
Note
Sets the check_function.__datatyping_validate attribute.
Parameters: check_function (function) – Function that should be used to type check.
Example¶
The following example defines a “custom type”, that can only be positive integers.
from datatyping import validate, customtype
@customtype
def positive_int(i):
if i < 1:
raise TypeError('%d is not positive' % i)
validate([positive_int], [1, 2, 3, 4])
validate([positive_int], [1, 2, 3, -4])
TypeError: -4 is not positive