examples.17_coerce_to_type
Demonstrates the use of CoerceToType to normalize numeric types.
This example shows:
- How integers can be coerced to floats.
- How floats can be coerced to Decimals via string conversion.
- How integers can be coerced to Fractions.
- Each coercion returns a
ResponsewithStatus.OKand a new, converted value.
Run directly:
python examples/17_coerce_to_type.py
Expected output:
int->float: 3.0 float->Decimal: 0.1 int->Fraction: 2
1"""Demonstrates the use of :class:`CoerceToType` to normalize numeric types. 2 3This example shows: 4 * How integers can be coerced to floats. 5 * How floats can be coerced to Decimals via string conversion. 6 * How integers can be coerced to Fractions. 7 * Each coercion returns a `Response` with `Status.OK` and a new, converted value. 8 9Run directly: 10 11 python examples/17_coerce_to_type.py 12 13Expected output: 14 15 int->float: 3.0 16 float->Decimal: 0.1 17 int->Fraction: 2 18""" 19 20import sys 21import pathlib 22from decimal import Decimal 23from fractions import Fraction 24 25# --------------------------------------------------------------------------- 26# Make repo root importable when running this file directly 27# --------------------------------------------------------------------------- 28sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) 29 30from constrained_values.strategies import CoerceToType 31 32 33def main() -> None: 34 """Run the CoerceToType demonstration. 35 36 Uses :class:`CoerceToType` to convert various numeric types. 37 38 Steps: 39 1. Coerce an integer to a `float`. 40 2. Coerce a `float` to a `Decimal` (via string conversion). 41 3. Coerce an integer to a `Fraction`. 42 43 Prints: 44 * `"int->float: 3.0"` 45 * `"float->Decimal: 0.1"` 46 * `"int->Fraction: 2"` 47 """ 48 print("int->float:", CoerceToType(float).transform(3).value) 49 print("float->Decimal:", CoerceToType(Decimal).transform(0.1).value) 50 print("int->Fraction:", CoerceToType(Fraction).transform(2).value) 51 52 53if __name__ == "__main__": 54 main()
def
main() -> None:
34def main() -> None: 35 """Run the CoerceToType demonstration. 36 37 Uses :class:`CoerceToType` to convert various numeric types. 38 39 Steps: 40 1. Coerce an integer to a `float`. 41 2. Coerce a `float` to a `Decimal` (via string conversion). 42 3. Coerce an integer to a `Fraction`. 43 44 Prints: 45 * `"int->float: 3.0"` 46 * `"float->Decimal: 0.1"` 47 * `"int->Fraction: 2"` 48 """ 49 print("int->float:", CoerceToType(float).transform(3).value) 50 print("float->Decimal:", CoerceToType(Decimal).transform(0.1).value) 51 print("int->Fraction:", CoerceToType(Fraction).transform(2).value)
Run the CoerceToType demonstration.
Uses CoerceToType to convert various numeric types.
Steps:
- Coerce an integer to a
float.- Coerce a
floatto aDecimal(via string conversion).- Coerce an integer to a
Fraction.
Prints:
"int->float: 3.0""float->Decimal: 0.1""int->Fraction: 2"