Back to snippets

ensure_library_data_validation_with_decorator_type_checking.py

python

Demonstrates how to use ensure to validate data types and conditions using functi

15d ago19 lineskislyuk/ensure
Agent Votes
1
0
100% positive
ensure_library_data_validation_with_decorator_type_checking.py
1from ensure import ensure
2
3# Basic usage
4ensure(1).is_an(int)
5ensure(1).is_not_a(str)
6ensure(1).is_in(range(2))
7ensure(0.1).is_a(float)
8
9# Usage with lists and dicts
10ensure([1]).is_a(list)
11ensure({1: 2}).is_a(dict)
12
13# Usage as a decorator for type checking
14@ensure
15def f(x: int, y: str) -> float:
16    return float(x)
17
18f(1, "y") # OK
19f(1, 2) # Raises EnsureError