Getting Started¶
The bread and butter of datatyping is the validate function.
-
datatyping.
validate
(structure, data, *, strict=True)¶ Verify that values in a dataset are of correct types.
Example
>>> validate([str], ['a', 'b', 'c']) >>> validate( ... {'id': int, 'lucky_numbers': [int]}, ... {'id': 700, 'lucky_numbers': [1, 3, 7, 13]} ... ) >>> validate([int], [1, 2, 3, 4.5]) TypeError: 4.5 is of type float, expected type int.
Parameters: - structure (type or collection of types) – The data structure that data should follow.
- data (anything) – The data you want type checked.
- strict (bool) – Dicts in data must have the exact keys specified in structure. No more.
Raises: TypeError
– If an elements in data has wrong type.ValueError
– If the length of structure doesn’t make sense for validating data.KeyError
– If a dict in data misses a key or strict is True and a dict has keys not in structure.
Examples¶
The following short examples are meant to clarify. If these are not sufficient, let me know (or maybe check out the unit tests :).
>>> validate([int, str], [1, 'a'])
>>> validate([[int], [str]], [[1, 2, 3], ['a', 'b', 'c'])
>>> validate([dict], [{'can have': 1}, {'any keys': 2}])
>>> validate({'a': int, 'b': str}, {'a': 4, 'b': 'c'})
>>> validate({'a': int}, {'a': 2, 'b': 'oops'})
KeyError: {'b'}
>>> validate({'a': int}, {'a': 2, 'b': 'yay'}, strict=False)