examples.25_uuid_value

Demonstrates transforming a string into a uuid.UUID and inspecting the resulting UUID object (including its version).

This example shows:
  • How to accept a string input and parse it into uuid.UUID.
  • How failures produce Status.EXCEPTION with an explanatory message.
  • How to access fields on the resulting UUID (e.g., .version) when OK.
Run directly:

python examples/25_uuid_value.py

Expected output (example):

x: OK 12345678-1234-5678-1234-567812345678
y: OK 4
 1"""Demonstrates transforming a string into a `uuid.UUID` and inspecting the
 2resulting UUID object (including its version).
 3
 4This example shows:
 5  * How to accept a string input and parse it into `uuid.UUID`.
 6  * How failures produce `Status.EXCEPTION` with an explanatory message.
 7  * How to access fields on the resulting UUID (e.g., `.version`) when OK.
 8
 9Run directly:
10
11    python examples/25_uuid_value.py
12
13Expected output (example):
14
15    x: OK 12345678-1234-5678-1234-567812345678
16    y: OK 4
17"""
18
19import sys
20import pathlib
21import uuid
22from typing import 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, TypeValidationStrategy
30from constrained_values.value import (
31    TransformationStrategy,
32    ConstrainedValue,
33    PipeLineStrategy,
34)
35
36
37class ToUUID(TransformationStrategy[str, uuid.UUID]):
38    """Transform a string into a `uuid.UUID`."""
39
40    def transform(self, value: str) -> Response[uuid.UUID]:
41        """Attempt to parse a UUID from the input string.
42
43        Args:
44            value: The input string to parse as a UUID.
45
46        Returns:
47            Response[uuid.UUID]:
48                * `status = Status.OK`, `details = "uuid"`, and a `uuid.UUID`
49                  instance when parsing succeeds.
50                * `status = Status.EXCEPTION` and an error message when parsing
51                  fails.
52        """
53        try:
54            return Response(Status.OK, "uuid", uuid.UUID(value))
55        except Exception as e:
56            return Response(Status.EXCEPTION, f"bad uuid: {e}", None)
57
58
59class UUIDValue(ConstrainedValue[uuid.UUID]):
60    """A `ConstrainedValue` that parses strings into `uuid.UUID`."""
61
62    def get_strategies(self) -> List[PipeLineStrategy]:
63        """Return the parsing pipeline (string → UUID)."""
64        return [TypeValidationStrategy(str), ToUUID()]
65
66
67def main() -> None:
68    """Run the UUID parsing demonstration.
69
70    Steps:
71        1. Parse a fixed UUID string and print either the parsed value (OK)
72           or the error details (EXCEPTION).
73        2. Parse a newly generated v4 UUID string and print its `.version`.
74
75    Prints:
76        * `"x: OK <uuid-string>"` or `"x: EXCEPTION <details>"`
77        * `"y: OK 4"` (for a freshly generated v4 UUID)
78    """
79    x = UUIDValue("12345678-1234-5678-1234-567812345678")
80    print("x:", x.status.name, x.value if x.ok else x.details)
81
82    y = UUIDValue(str(uuid.uuid4()))
83    print("y:", y.status.name, y.value.version if y.ok else y.details)
84
85
86if __name__ == "__main__":
87    main()
class ToUUID(constrained_values.value.TransformationStrategy[str, uuid.UUID]):
38class ToUUID(TransformationStrategy[str, uuid.UUID]):
39    """Transform a string into a `uuid.UUID`."""
40
41    def transform(self, value: str) -> Response[uuid.UUID]:
42        """Attempt to parse a UUID from the input string.
43
44        Args:
45            value: The input string to parse as a UUID.
46
47        Returns:
48            Response[uuid.UUID]:
49                * `status = Status.OK`, `details = "uuid"`, and a `uuid.UUID`
50                  instance when parsing succeeds.
51                * `status = Status.EXCEPTION` and an error message when parsing
52                  fails.
53        """
54        try:
55            return Response(Status.OK, "uuid", uuid.UUID(value))
56        except Exception as e:
57            return Response(Status.EXCEPTION, f"bad uuid: {e}", None)

Transform a string into a uuid.UUID.

def transform(self, value: str) -> constrained_values.Response[uuid.UUID]:
41    def transform(self, value: str) -> Response[uuid.UUID]:
42        """Attempt to parse a UUID from the input string.
43
44        Args:
45            value: The input string to parse as a UUID.
46
47        Returns:
48            Response[uuid.UUID]:
49                * `status = Status.OK`, `details = "uuid"`, and a `uuid.UUID`
50                  instance when parsing succeeds.
51                * `status = Status.EXCEPTION` and an error message when parsing
52                  fails.
53        """
54        try:
55            return Response(Status.OK, "uuid", uuid.UUID(value))
56        except Exception as e:
57            return Response(Status.EXCEPTION, f"bad uuid: {e}", None)

Attempt to parse a UUID from the input string.

Arguments:
  • value: The input string to parse as a UUID.
Returns:

Response[uuid.UUID]: * status = Status.OK, details = "uuid", and a uuid.UUID instance when parsing succeeds. * status = Status.EXCEPTION and an error message when parsing fails.

class UUIDValue(constrained_values.value.ConstrainedValue[uuid.UUID]):
60class UUIDValue(ConstrainedValue[uuid.UUID]):
61    """A `ConstrainedValue` that parses strings into `uuid.UUID`."""
62
63    def get_strategies(self) -> List[PipeLineStrategy]:
64        """Return the parsing pipeline (string → UUID)."""
65        return [TypeValidationStrategy(str), ToUUID()]

A ConstrainedValue that parses strings into uuid.UUID.

def get_strategies(self) -> List[constrained_values.value.PipeLineStrategy]:
63    def get_strategies(self) -> List[PipeLineStrategy]:
64        """Return the parsing pipeline (string → UUID)."""
65        return [TypeValidationStrategy(str), ToUUID()]

Return the parsing pipeline (string → UUID).

Inherited Members
constrained_values.value.ConstrainedValue
ConstrainedValue
status
details
value
unwrap
ok
def main() -> None:
68def main() -> None:
69    """Run the UUID parsing demonstration.
70
71    Steps:
72        1. Parse a fixed UUID string and print either the parsed value (OK)
73           or the error details (EXCEPTION).
74        2. Parse a newly generated v4 UUID string and print its `.version`.
75
76    Prints:
77        * `"x: OK <uuid-string>"` or `"x: EXCEPTION <details>"`
78        * `"y: OK 4"` (for a freshly generated v4 UUID)
79    """
80    x = UUIDValue("12345678-1234-5678-1234-567812345678")
81    print("x:", x.status.name, x.value if x.ok else x.details)
82
83    y = UUIDValue(str(uuid.uuid4()))
84    print("y:", y.status.name, y.value.version if y.ok else y.details)

Run the UUID parsing demonstration.

Steps:
  1. Parse a fixed UUID string and print either the parsed value (OK) or the error details (EXCEPTION).
  2. Parse a newly generated v4 UUID string and print its .version.
Prints:
  • "x: OK <uuid-string>" or "x: EXCEPTION <details>"
  • "y: OK 4" (for a freshly generated v4 UUID)