examples.example_2

Example: Using RangeValue with a custom transform (Fahrenheit → Celsius).

This demo shows how to subclass RangeValue and override get_custom_strategies() to insert a transformation step into the pipeline.

  • Input values are provided in Fahrenheit (int or float).
  • A FahrenheitToCelsius transformation converts them to Celsius.
  • The resulting Celsius values are validated against a range of -10°C .. 40°C.
  • Results are rounded to two decimal places.
 1"""
 2Example: Using RangeValue with a custom transform (Fahrenheit → Celsius).
 3
 4This demo shows how to subclass RangeValue and override
 5`get_custom_strategies()` to insert a transformation step into the pipeline.
 6
 7- Input values are provided in Fahrenheit (int or float).
 8- A FahrenheitToCelsius transformation converts them to Celsius.
 9- The resulting Celsius values are validated against a range of -10°C .. 40°C.
10- Results are rounded to two decimal places.
11"""
12import sys, pathlib
13from constrained_values import Response, Status, RangeValue
14from constrained_values.constants import DEFAULT_SUCCESS_MESSAGE
15from constrained_values.value import TransformationStrategy
16
17# Make repo root importable when running this file directly
18sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
19
20class FahrenheitToCelsius(TransformationStrategy[float, float]):
21    """
22    Define a transformation strategy for Fahrenheit.
23    input and output types are float
24    """
25    def transform(self, value: float) -> Response[float]:
26        try:
27            c = round((float(value) - 32.0) * (5.0 / 9.0),2)
28            return Response(Status.OK, DEFAULT_SUCCESS_MESSAGE, c)
29        except Exception as e:
30            return Response(Status.EXCEPTION, str(e), None)
31
32
33class FahrenheitToCelsiusValue(RangeValue[float]):
34    """
35    Valid Celsius value between -10 and 40, inclusive.
36    Accepts input as Fahrenheit (int/float).
37    Fahrenheit is converted internally to Celsius before validation.
38    """
39    def __init__(self, value: int | float):
40        super().__init__(value, -10.0, 40.0)
41
42    def get_custom_strategies(self):
43         return [FahrenheitToCelsius()]
44
45def main():
46    print("\n=== Fahrenheit inputs (converted to Celsius) ===")
47    for val in [50, 50.36, 72]:
48        cv = FahrenheitToCelsiusValue(val)
49        print(f"Input {val!r}F → status={cv.status}, value={cv.value}°C")
50
51    print("\n=== Out of range examples ===")
52    for val in [-40, 10, 122]:
53        cv = FahrenheitToCelsiusValue(val)
54        print(f"Input {val!r} → status={cv.status}, \n details={cv.details}")
55
56if __name__ == "__main__":
57    main()
class FahrenheitToCelsius(constrained_values.value.TransformationStrategy[float, float]):
21class FahrenheitToCelsius(TransformationStrategy[float, float]):
22    """
23    Define a transformation strategy for Fahrenheit.
24    input and output types are float
25    """
26    def transform(self, value: float) -> Response[float]:
27        try:
28            c = round((float(value) - 32.0) * (5.0 / 9.0),2)
29            return Response(Status.OK, DEFAULT_SUCCESS_MESSAGE, c)
30        except Exception as e:
31            return Response(Status.EXCEPTION, str(e), None)

Define a transformation strategy for Fahrenheit. input and output types are float

def transform(self, value: float) -> constrained_values.Response[float]:
26    def transform(self, value: float) -> Response[float]:
27        try:
28            c = round((float(value) - 32.0) * (5.0 / 9.0),2)
29            return Response(Status.OK, DEFAULT_SUCCESS_MESSAGE, c)
30        except Exception as e:
31            return Response(Status.EXCEPTION, str(e), None)

Transform value and return a Response.

Arguments:
  • value (InT): Input value to transform.
Returns:

Response[OutT]: The transformed value with status and details.

class FahrenheitToCelsiusValue(constrained_values.constrained_value_types.RangeValue[float]):
34class FahrenheitToCelsiusValue(RangeValue[float]):
35    """
36    Valid Celsius value between -10 and 40, inclusive.
37    Accepts input as Fahrenheit (int/float).
38    Fahrenheit is converted internally to Celsius before validation.
39    """
40    def __init__(self, value: int | float):
41        super().__init__(value, -10.0, 40.0)
42
43    def get_custom_strategies(self):
44         return [FahrenheitToCelsius()]

Valid Celsius value between -10 and 40, inclusive. Accepts input as Fahrenheit (int/float). Fahrenheit is converted internally to Celsius before validation.

FahrenheitToCelsiusValue(value: int | float)
40    def __init__(self, value: int | float):
41        super().__init__(value, -10.0, 40.0)
def get_custom_strategies(self):
43    def get_custom_strategies(self):
44         return [FahrenheitToCelsius()]
Inherited Members
constrained_values.constrained_value_types.RangeValue
infer_valid_types_from_value
get_strategies
constrained_values.value.ConstrainedValue
status
details
value
unwrap
ok
def main():
46def main():
47    print("\n=== Fahrenheit inputs (converted to Celsius) ===")
48    for val in [50, 50.36, 72]:
49        cv = FahrenheitToCelsiusValue(val)
50        print(f"Input {val!r}F → status={cv.status}, value={cv.value}°C")
51
52    print("\n=== Out of range examples ===")
53    for val in [-40, 10, 122]:
54        cv = FahrenheitToCelsiusValue(val)
55        print(f"Input {val!r} → status={cv.status}, \n details={cv.details}")