examples.example_1

The most basic use case is ensuring a value falls within a specific range. Instead of passing an integer around and checking its bounds everywhere, we create an Age type by defining a class.

 1"""
 2The most basic use case is ensuring a value falls within a specific range.
 3Instead of passing an integer around and checking its bounds everywhere, 
 4we create an `Age` type by defining a class.
 5"""
 6import sys, pathlib
 7from constrained_values import RangeValue
 8
 9# Make repo root importable when running this file directly
10sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
11
12
13def main():
14    # Define an 'Age' type that must be an integer between 0 and 120.
15    class Age(RangeValue[int]):
16        def __init__(self, value):
17            super().__init__(value, 10, 120)
18
19    # Now, let's use our new Age type.
20    valid_age = Age(30)
21    invalid_age = Age(150)
22    invalid_age_by_type = Age("21")
23    another_valid_age = Age(32)
24
25    print(f"Another valid age: {another_valid_age.value}, is greater than valid age: {valid_age.value} ? {another_valid_age > valid_age}")
26    #Output: Another valid age: 32, is greater than valid age: 30 ? True
27
28    print(f"Valid age: {valid_age.value}, Is OK: {valid_age.ok}")
29    # Output: Valid age: 30, Is OK: True
30
31    print(f"Invalid age: {invalid_age.value}, Is OK: {invalid_age.ok}")
32    # Output: Invalid age: None, Is OK: False
33
34    print(f"Error details: {invalid_age.details}")
35    # Output: Value must be less than or equal to 120, got 150
36
37    print(f"Error details: {invalid_age_by_type.details}")
38    # Output: Error details: Value must be one of 'int', got 'str'
39
40
41if __name__ == "__main__":
42    main()
def main():
14def main():
15    # Define an 'Age' type that must be an integer between 0 and 120.
16    class Age(RangeValue[int]):
17        def __init__(self, value):
18            super().__init__(value, 10, 120)
19
20    # Now, let's use our new Age type.
21    valid_age = Age(30)
22    invalid_age = Age(150)
23    invalid_age_by_type = Age("21")
24    another_valid_age = Age(32)
25
26    print(f"Another valid age: {another_valid_age.value}, is greater than valid age: {valid_age.value} ? {another_valid_age > valid_age}")
27    #Output: Another valid age: 32, is greater than valid age: 30 ? True
28
29    print(f"Valid age: {valid_age.value}, Is OK: {valid_age.ok}")
30    # Output: Valid age: 30, Is OK: True
31
32    print(f"Invalid age: {invalid_age.value}, Is OK: {invalid_age.ok}")
33    # Output: Invalid age: None, Is OK: False
34
35    print(f"Error details: {invalid_age.details}")
36    # Output: Value must be less than or equal to 120, got 150
37
38    print(f"Error details: {invalid_age_by_type.details}")
39    # Output: Error details: Value must be one of 'int', got 'str'