Repository: antonagestam/phantom-types (language: python)

Issue:
Make `Interval` parse strings



Discussion / hints:

Fix patch:
diff --git a/phantom/interval.py b/phantom/interval.py
index a7fa3b5..a15c28f 100644
--- a/phantom/interval.py
+++ b/phantom/interval.py
@@ -35,6 +35,7 @@ def take_portion(portion: Portion, whole: Natural) -> float:
 from .utils import resolve_class_attr
 
 N = TypeVar("N", bound=float)
+Derived = TypeVar("Derived", bound="Interval")
 
 
 class IntervalCheck(Protocol):
@@ -80,6 +81,12 @@ def __init_subclass__(
             **kwargs,
         )
 
+    @classmethod
+    def parse(cls: type[Derived], instance: object) -> Derived:
+        return super().parse(
+            cls.__bound__(instance) if isinstance(instance, str) else instance
+        )
+
 
 def _format_limit(value: float) -> str:
     if value == inf:


Test patch:
diff --git a/tests/test_interval.py b/tests/test_interval.py
index 1d9c2d8..6f2597c 100644
--- a/tests/test_interval.py
+++ b/tests/test_interval.py
@@ -3,6 +3,7 @@
 from phantom.interval import Interval
 from phantom.interval import Natural
 from phantom.interval import NegativeInt
+from phantom.interval import Open
 from phantom.interval import Portion
 
 
@@ -13,6 +14,12 @@ def test_subclassing_without_check_raises(self):
             class I(Interval, abstract=False):  # noqa: E742
                 ...
 
+    def test_parse_coerces_str(self):
+        class Great(int, Open, low=10):
+            ...
+
+        assert Great.parse("10") == 10
+
 
 parametrize_negative_ints = pytest.mark.parametrize("i", (-10, -1, -0, +0))
 parametrize_positive_ints = pytest.mark.parametrize("i", (10, 1, +0, -0))