examples.07_str_and_format
Demonstrates how valid and invalid ConstrainedValue objects behave when
formatted with str() or format().
This example shows:
- A successful value supports numeric formatting (e.g.,
.2f).- A failed value falls back to
str()representation when formatting fails.- The
detailsfield differentiates success vs. failure.
Run directly:
python examples/07_str_and_format.py
Expected output:
format ok .2f: 12.35 format bad .2f (falls back to str):
str(bad):
1"""Demonstrates how valid and invalid `ConstrainedValue` objects behave when 2formatted with `str()` or `format()`. 3 4This example shows: 5 * A successful value supports numeric formatting (e.g., `.2f`). 6 * A failed value falls back to `str()` representation when formatting fails. 7 * The `details` field differentiates success vs. failure. 8 9Run directly: 10 11 python examples/07_str_and_format.py 12 13Expected output: 14 15 format ok .2f: 12.35 16 format bad .2f (falls back to str): <invalid BadF: boom fmt> 17 str(bad): <invalid BadF: boom fmt> 18""" 19 20import sys 21import pathlib 22from typing import Any, List 23 24# --------------------------------------------------------------------------- 25# Make repo root importable when running this file directly 26# --------------------------------------------------------------------------- 27sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) 28 29from constrained_values import Response, Status 30from constrained_values.value import ( 31 TransformationStrategy, 32 ConstrainedValue, 33 PipeLineStrategy, 34) 35 36 37class Pass(TransformationStrategy[Any, Any]): 38 """A transformation strategy that always succeeds. 39 40 Produces an `OK` response with the input value unchanged. 41 """ 42 43 def transform(self, value: Any) -> Response[Any]: 44 """Return an OK response with the input value. 45 46 Args: 47 value: Any input value to pass through. 48 49 Returns: 50 Response[Any]: Contains `status=Status.OK`, 51 `details='ok fmt'`, and the same `value`. 52 """ 53 return Response(status=Status.OK, details="ok fmt", value=value) 54 55 56class Fail(TransformationStrategy[Any, Any]): 57 """A transformation strategy that always fails. 58 59 Used to demonstrate how formatting behaves for invalid constrained values. 60 """ 61 62 def transform(self, value: Any) -> Response[Any]: 63 """Return a failed response. 64 65 Args: 66 value: Any input value (ignored). 67 68 Returns: 69 Response[Any]: Contains `status=Status.EXCEPTION`, 70 `details='boom fmt'`, and `value=None`. 71 """ 72 return Response(status=Status.EXCEPTION, details="boom fmt", value=None) 73 74 75class GoodF(ConstrainedValue[float]): 76 """A `ConstrainedValue[float]` that always succeeds.""" 77 78 def get_strategies(self) -> List[PipeLineStrategy]: 79 """Return a one-step success pipeline.""" 80 return [Pass()] 81 82 83class BadF(ConstrainedValue[float]): 84 """A `ConstrainedValue[float]` that always fails.""" 85 86 def get_strategies(self) -> List[PipeLineStrategy]: 87 """Return a one-step failure pipeline.""" 88 return [Fail()] 89 90 91def main() -> None: 92 """Run the `__str__` and `__format__` demonstration. 93 94 Creates two constrained values: 95 * `GoodF` → succeeds and supports numeric formatting (e.g., `".2f"`). 96 * `BadF` → fails and falls back to its `str()` representation. 97 98 Prints: 99 * Formatted output for the successful value (`12.35`) 100 * Formatted output for the failed value (string fallback) 101 * Direct `str()` representation of the failed value 102 """ 103 ok = GoodF(12.3456) 104 bad = BadF(12.3456) 105 106 print("format ok .2f:", format(ok, ".2f")) 107 print("format bad .2f (falls back to str):", format(bad, ".2f")) 108 print("str(bad):", str(bad)) 109 110 111if __name__ == "__main__": 112 main()
38class Pass(TransformationStrategy[Any, Any]): 39 """A transformation strategy that always succeeds. 40 41 Produces an `OK` response with the input value unchanged. 42 """ 43 44 def transform(self, value: Any) -> Response[Any]: 45 """Return an OK response with the input value. 46 47 Args: 48 value: Any input value to pass through. 49 50 Returns: 51 Response[Any]: Contains `status=Status.OK`, 52 `details='ok fmt'`, and the same `value`. 53 """ 54 return Response(status=Status.OK, details="ok fmt", value=value)
A transformation strategy that always succeeds.
Produces an OK response with the input value unchanged.
44 def transform(self, value: Any) -> Response[Any]: 45 """Return an OK response with the input value. 46 47 Args: 48 value: Any input value to pass through. 49 50 Returns: 51 Response[Any]: Contains `status=Status.OK`, 52 `details='ok fmt'`, and the same `value`. 53 """ 54 return Response(status=Status.OK, details="ok fmt", value=value)
Return an OK response with the input value.
Arguments:
- value: Any input value to pass through.
Returns:
Response[Any]: Contains
status=Status.OK,details='ok fmt', and the samevalue.
57class Fail(TransformationStrategy[Any, Any]): 58 """A transformation strategy that always fails. 59 60 Used to demonstrate how formatting behaves for invalid constrained values. 61 """ 62 63 def transform(self, value: Any) -> Response[Any]: 64 """Return a failed response. 65 66 Args: 67 value: Any input value (ignored). 68 69 Returns: 70 Response[Any]: Contains `status=Status.EXCEPTION`, 71 `details='boom fmt'`, and `value=None`. 72 """ 73 return Response(status=Status.EXCEPTION, details="boom fmt", value=None)
A transformation strategy that always fails.
Used to demonstrate how formatting behaves for invalid constrained values.
63 def transform(self, value: Any) -> Response[Any]: 64 """Return a failed response. 65 66 Args: 67 value: Any input value (ignored). 68 69 Returns: 70 Response[Any]: Contains `status=Status.EXCEPTION`, 71 `details='boom fmt'`, and `value=None`. 72 """ 73 return Response(status=Status.EXCEPTION, details="boom fmt", value=None)
Return a failed response.
Arguments:
- value: Any input value (ignored).
Returns:
Response[Any]: Contains
status=Status.EXCEPTION,details='boom fmt', andvalue=None.
76class GoodF(ConstrainedValue[float]): 77 """A `ConstrainedValue[float]` that always succeeds.""" 78 79 def get_strategies(self) -> List[PipeLineStrategy]: 80 """Return a one-step success pipeline.""" 81 return [Pass()]
A ConstrainedValue[float] that always succeeds.
79 def get_strategies(self) -> List[PipeLineStrategy]: 80 """Return a one-step success pipeline.""" 81 return [Pass()]
Return a one-step success pipeline.
Inherited Members
- constrained_values.value.ConstrainedValue
- ConstrainedValue
- status
- details
- value
- unwrap
- ok
84class BadF(ConstrainedValue[float]): 85 """A `ConstrainedValue[float]` that always fails.""" 86 87 def get_strategies(self) -> List[PipeLineStrategy]: 88 """Return a one-step failure pipeline.""" 89 return [Fail()]
A ConstrainedValue[float] that always fails.
87 def get_strategies(self) -> List[PipeLineStrategy]: 88 """Return a one-step failure pipeline.""" 89 return [Fail()]
Return a one-step failure pipeline.
Inherited Members
- constrained_values.value.ConstrainedValue
- ConstrainedValue
- status
- details
- value
- unwrap
- ok
92def main() -> None: 93 """Run the `__str__` and `__format__` demonstration. 94 95 Creates two constrained values: 96 * `GoodF` → succeeds and supports numeric formatting (e.g., `".2f"`). 97 * `BadF` → fails and falls back to its `str()` representation. 98 99 Prints: 100 * Formatted output for the successful value (`12.35`) 101 * Formatted output for the failed value (string fallback) 102 * Direct `str()` representation of the failed value 103 """ 104 ok = GoodF(12.3456) 105 bad = BadF(12.3456) 106 107 print("format ok .2f:", format(ok, ".2f")) 108 print("format bad .2f (falls back to str):", format(bad, ".2f")) 109 print("str(bad):", str(bad))
Run the __str__ and __format__ demonstration.
Creates two constrained values:
Prints:
- Formatted output for the successful value (
12.35)- Formatted output for the failed value (string fallback)
- Direct
str()representation of the failed value