Skip to content

Fixes and features - #206

Merged
KotlinIsland merged 10 commits into
mainfrom
fixes-and-features
Sep 11, 2026
Merged

KotlinIsland merged 10 commits into
mainfrom
fixes-and-features

Conversation

@KotlinIsland

Copy link
Copy Markdown
Owner

No description provided.

@github-actions

github-actions Bot commented Sep 10, 2026

Copy link
Copy Markdown
Contributor

by ecosystem round-trip

base: fe9ce5febee021585ebf4aa9bab4649603300baf (merge base) → head: 206/merge

regressions: 1, changed: 11022, improvements: 0, error changes: 0 (across 25262 files in 148 projects)

⚠️ 15 project(s) fail to round-trip on both base and head, so this check says nothing about them.

❌ regressions (built on base, now fails)

alerta —
build: killed: timed out after 900s

ℹ️ changed round-trip output

DateType — _by_sourcemap.py
--- base/_by_sourcemap.py
+++ head/_by_sourcemap.py
@@ -5,5 +5,5 @@
... 6605 characters elided ...
     "/tmp/tmpcnq1x8cc/DateType/build/tryit.py": {"by": "sha256:c69dd12f5097fd2d789de3a1af05ba4204b15930ca0ed7e3fbb5848d6b3beca5", "py": "sha256:1a87876734fb3051e09f9114905d2e76c776dbc2237aadc0e1dec217409c906d"},
 }
DateType — datetype/__init__.py
--- base/datetype/__init__.py
+++ head/datetype/__init__.py
@@ -632,5 +632,5 @@
     dt: Date | DateTime[_tzinfo | None] | Time[_tzinfo | None],
 ) -> _datetime | _date | _time:
-    if False:
+    if isinstance(dt, (_date, _time, _datetime)):
         return dt
     else:
DateType — datetype/_by_runtime.py
(only produced on head)
DateType — datetype/test/test_datetype.py
--- base/datetype/test/test_datetype.py
+++ head/datetype/test/test_datetype.py
@@ -1,10 +1,3 @@
-def _soundness_check(_v, _t):
-    if not isinstance(_v, _t):
-        raise TypeError(
-            f"type soundness violation: expected {getattr(_t, '__name__', _t)}, "
-            f"got {type(_v).__name__}"
-        )
-    return _v
-
+from datetype._by_runtime import _soundness_check
 lazy from datetime import date, datetime, time, timedelta, timezone
 lazy from os import chdir, getcwd, popen
Expression — README.py
--- base/README.py
+++ head/README.py
@@ -17,4 +17,12 @@
 lazy from ty_extensions import JustFloat
 lazy from typing import Callable, Literal
+def _soundness_check(_v, _t):
+    if not isinstance(_v, _t):
+        raise TypeError(
+            f"type soundness violation: expected {getattr(_t, '__name__', _t)}, "
+            f"got {type(_v).__name__}"
+        )
+    return _v
+
 class Optional:
     def __init__(self, value):
@@ -165,25 +173,4 @@
     return a == b
 
-def _parametric_is_lenient(value, alias, variances):
-    # the checked-cast form: a value that records no reification has no
-    # arguments to check, so the base class test is the whole guarantee. this is
-    # what keeps `[1, 2] cast list[int]` legal while still rejecting a value
-    # whose recorded arguments contradict the target
-    alias = _by_alias(getattr(alias, "__value__", alias))
-    origin = getattr(alias, "__origin__", alias)
-    if not isinstance(value, origin):
-        return False
-    if not _by_generic_args(value, origin):
-        return True
-    return _parametric_is(value, alias, variances)
-
... 582 characters elided ...
         return Shape(rectangle=Rectangle(width, length))
 
     @staticmethod
-    def Circle(radius: JustFloat) -> Literal["Shape"]:
+    def Circle(radius: JustFloat) -> Shape:
         """Optional static method for creating a tagged union case"""
         return Shape(circle=Circle(radius))
Expression — _by_sourcemap.py
--- base/_by_sourcemap.py
+++ head/_by_sourcemap.py
@@ -2,89 +2,89 @@
 # the two tables share their keys: the generated path, spelled as it is here
 SOURCEMAP = {
... 238984 characters elided ...
     "/tmp/tmpkx1wi2_d/Expression/build/tests/utils.py": {"by": "sha256:d2c23ef1222fd08ceebde01e3be6e2cf4b1295a5637717964f6a77682ab0535c", "py": "sha256:d2c23ef1222fd08ceebde01e3be6e2cf4b1295a5637717964f6a77682ab0535c"},
 }
Expression — docs/guides/choosing-a-type.py
--- base/docs/guides/choosing-a-type.py
+++ head/docs/guides/choosing-a-type.py
@@ -19,4 +19,12 @@
 Use `Option` when absence is sufficient information:
 """
+def _soundness_check(_v, _t):
+    if not isinstance(_v, _t):
+        raise TypeError(
+            f"type soundness violation: expected {getattr(_t, '__name__', _t)}, "
+            f"got {type(_v).__name__}"
+        )
+    return _v
+
 class Optional:
     def __init__(self, value):
@@ -167,25 +175,4 @@
     return a == b
 
-def _parametric_is_lenient(value, alias, variances):
-    # the checked-cast form: a value that records no reification has no
-    # arguments to check, so the base class test is the whole guarantee. this is
-    # what keeps `[1, 2] cast list[int]` legal while still rejecting a value
-    # whose recorded arguments contradict the target
-    alias = _by_alias(getattr(alias, "__value__", alias))
-    origin = getattr(alias, "__origin__", alias)
-    if not isinstance(value, origin):
-        return False
-    if not _by_generic_args(value, origin):
-        return True
-    return _parametric_is(value, alias, variances)
-
-def _soundness_check(_v, _t):
-    if not isinstance(_v, _t):
-        raise TypeError(
-            f"type soundness violation: expected {getattr(_t, '__name__', _t)}, "
-            f"got {type(_v).__name__}"
-        )
-    return _v
-
 def _soundness_parametric(_v, _alias, _variances):
     _alias = _by_alias(_alias)
Expression — docs/guides/collection-types.py
--- base/docs/guides/collection-types.py
+++ head/docs/guides/collection-types.py
@@ -18,4 +18,12 @@
 useful for a large input or a multi-stage workflow.
 """
+def _soundness_check(_v, _t):
+    if not isinstance(_v, _t):
+        raise TypeError(
+            f"type soundness violation: expected {getattr(_t, '__name__', _t)}, "
+            f"got {type(_v).__name__}"
+        )
+    return _v
+
 def _by_type_param_defaults(args):
     # a class records its generic bases *unsubstituted* — `class L[T = Never]
@@ -156,25 +164,4 @@
     return a == b
 
-def _parametric_is_lenient(value, alias, variances):
-    # the checked-cast form: a value that records no reification has no
-    # arguments to check, so the base class test is the whole guarantee. this is
-    # what keeps `[1, 2] cast list[int]` legal while still rejecting a value
-    # whose recorded arguments contradict the target
-    alias = _by_alias(getattr(alias, "__value__", alias))
-    origin = getattr(alias, "__origin__", alias)
-    if not isinstance(value, origin):
-        return False
-    if not _by_generic_args(value, origin):
... 74 characters elided ...
-
-def _soundness_check(_v, _t):
-    if not isinstance(_v, _t):
-        raise TypeError(
-            f"type soundness violation: expected {getattr(_t, '__name__', _t)}, "
-            f"got {type(_v).__name__}"
-        )
-    return _v
-
 def _soundness_parametric(_v, _alias, _variances):
     _alias = _by_alias(_alias)
Expression — docs/guides/domain-modeling.py
--- base/docs/guides/domain-modeling.py
+++ head/docs/guides/domain-modeling.py
@@ -26,9 +26,9 @@
 
     @staticmethod
-    def Card(last_four: str) -> Literal["Payment"]:
+    def Card(last_four: str) -> Payment:
         return Payment(card=last_four)
 
     @staticmethod
-    def Cash() -> Literal["Payment"]:
+    def Cash() -> Payment:
         return Payment(cash=None)
Expression — docs/guides/effects.py
--- base/docs/guides/effects.py
+++ head/docs/guides/effects.py
@@ -6,4 +6,16 @@
 when several `Option` or `Result` steps need local variables and early termination.
 """
+def _soundness_check(_v, _t):
+    if not isinstance(_v, _t):
+        raise TypeError(
+            f"type soundness violation: expected {getattr(_t, '__name__', _t)}, "
+            f"got {type(_v).__name__}"
+        )
+    return _v
+
+def _soundness_iter(_it, _t):
+    for _x in _it:
+        yield _soundness_check(_x, _t)
+
 class Optional:
     def __init__(self, value):
@@ -154,29 +166,4 @@
     return a == b
 
-def _parametric_is_lenient(value, alias, variances):
-    # the checked-cast form: a value that records no reification has no
-    # arguments to check, so the base class test is the whole guarantee. this is
-    # what keeps `[1, 2] cast list[int]` legal while still rejecting a value
-    # whose recorded arguments contradict the target
-    alias = _by_alias(getattr(alias, "__value__", alias))
-    origin = getattr(alias, "__origin__", alias)
-    if not isinstance(value, origin):
-        return False
... 210 characters elided ...
-            f"type soundness violation: expected {getattr(_t, '__name__', _t)}, "
-            f"got {type(_v).__name__}"
-        )
-    return _v
-
-def _soundness_iter(_it, _t):
-    for _x in _it:
-        yield _soundness_check(_x, _t)
-
 def _soundness_parametric(_v, _alias, _variances):
     _alias = _by_alias(_alias)
Expression — docs/guides/error-handling.py
--- base/docs/guides/error-handling.py
+++ head/docs/guides/error-handling.py
@@ -6,4 +6,12 @@
 the error. `Ok(value)` holds a successful result; `Error(error)` holds the reason.
 """
+def _soundness_check(_v, _t):
+    if not isinstance(_v, _t):
+        raise TypeError(
+            f"type soundness violation: expected {getattr(_t, '__name__', _t)}, "
+            f"got {type(_v).__name__}"
+        )
+    return _v
+
 def _by_type_param_defaults(args):
     # a class records its generic bases *unsubstituted* — `class L[T = Never]
@@ -144,25 +152,4 @@
     return a == b
 
-def _parametric_is_lenient(value, alias, variances):
-    # the checked-cast form: a value that records no reification has no
-    # arguments to check, so the base class test is the whole guarantee. this is
-    # what keeps `[1, 2] cast list[int]` legal while still rejecting a value
-    # whose recorded arguments contradict the target
-    alias = _by_alias(getattr(alias, "__value__", alias))
-    origin = getattr(alias, "__origin__", alias)
-    if not isinstance(value, origin):
-        return False
... 119 characters elided ...
-
-def _soundness_check(_v, _t):
-    if not isinstance(_v, _t):
-        raise TypeError(
-            f"type soundness violation: expected {getattr(_t, '__name__', _t)}, "
-            f"got {type(_v).__name__}"
-        )
-    return _v
-
 def _soundness_parametric(_v, _alias, _variances):
     _alias = _by_alias(_alias)
Expression — docs/guides/getting-started.py
--- base/docs/guides/getting-started.py
+++ head/docs/guides/getting-started.py
@@ -20,4 +20,12 @@
 when a transformation has several named steps.
 """
+def _soundness_check(_v, _t):
+    if not isinstance(_v, _t):
+        raise TypeError(
+            f"type soundness violation: expected {getattr(_t, '__name__', _t)}, "
+            f"got {type(_v).__name__}"
+        )
+    return _v
+
 def _by_type_param_defaults(args):
     # a class records its generic bases *unsubstituted* — `class L[T = Never]
@@ -158,25 +166,4 @@
     return a == b
 
-def _parametric_is_lenient(value, alias, variances):
-    # the checked-cast form: a value that records no reification has no
-    # arguments to check, so the base class test is the whole guarantee. this is
-    # what keeps `[1, 2] cast list[int]` legal while still rejecting a value
-    # whose recorded arguments contradict the target
-    alias = _by_alias(getattr(alias, "__value__", alias))
-    origin = getattr(alias, "__origin__", alias)
-    if not isinstance(value, origin):
-        return False
-    if not _by_generic_args(value, origin):
... 74 characters elided ...
-
-def _soundness_check(_v, _t):
-    if not isinstance(_v, _t):
-        raise TypeError(
-            f"type soundness violation: expected {getattr(_t, '__name__', _t)}, "
-            f"got {type(_v).__name__}"
-        )
-    return _v
-
 def _soundness_parametric(_v, _alias, _variances):
     _alias = _by_alias(_alias)
Expression — docs/guides/optional-values.py
--- base/docs/guides/optional-values.py
+++ head/docs/guides/optional-values.py
@@ -7,4 +7,12 @@
 return type instead of relying on an unchecked `None`.
 """
+def _soundness_check(_v, _t):
+    if not isinstance(_v, _t):
+        raise TypeError(
+            f"type soundness violation: expected {getattr(_t, '__name__', _t)}, "
+            f"got {type(_v).__name__}"
+        )
+    return _v
+
 class Optional:
     def __init__(self, value):
@@ -155,25 +163,4 @@
     return a == b
 
-def _parametric_is_lenient(value, alias, variances):
-    # the checked-cast form: a value that records no reification has no
-    # arguments to check, so the base class test is the whole guarantee. this is
-    # what keeps `[1, 2] cast list[int]` legal while still rejecting a value
-    # whose recorded arguments contradict the target
-    alias = _by_alias(getattr(alias, "__value__", alias))
-    origin = getattr(alias, "__origin__", alias)
-    if not isinstance(value, origin):
-        return False
-    if not _by_generic_args(value, origin):
-        return True
-    return _parametric_is(value, alias, variances)
-
-def _soundness_check(_v, _t):
-    if not isinstance(_v, _t):
-        raise TypeError(
-            f"type soundness violation: expected {getattr(_t, '__name__', _t)}, "
-            f"got {type(_v).__name__}"
-        )
-    return _v
-
 def _soundness_parametric(_v, _alias, _variances):
     _alias = _by_alias(_alias)
Expression — docs/tutorial/containers.py
--- base/docs/tutorial/containers.py
+++ head/docs/tutorial/containers.py
@@ -10,4 +10,12 @@
 materialize its values until a consumer asks for them.
 """
+def _soundness_check(_v, _t):
+    if not isinstance(_v, _t):
+        raise TypeError(
+            f"type soundness violation: expected {getattr(_t, '__name__', _t)}, "
+            f"got {type(_v).__name__}"
+        )
+    return _v
+
 def _by_type_param_defaults(args):
     # a class records its generic bases *unsubstituted* — `class L[T = Never]
@@ -148,25 +156,4 @@
     return a == b
 
-def _parametric_is_lenient(value, alias, variances):
-    # the checked-cast form: a value that records no reification has no
-    # arguments to check, so the base class test is the whole guarantee. this is
-    # what keeps `[1, 2] cast list[int]` legal while still rejecting a value
-    # whose recorded arguments contradict the target
-    alias = _by_alias(getattr(alias, "__value__", alias))
-    origin = getattr(alias, "__origin__", alias)
-    if not isinstance(value, origin):
-        return False
-    if not _by_generic_args(value, origin):
... 74 characters elided ...
-
-def _soundness_check(_v, _t):
-    if not isinstance(_v, _t):
-        raise TypeError(
-            f"type soundness violation: expected {getattr(_t, '__name__', _t)}, "
-            f"got {type(_v).__name__}"
-        )
-    return _v
-
 def _soundness_parametric(_v, _alias, _variances):
     _alias = _by_alias(_alias)
Expression — docs/tutorial/data_modelling.py
--- base/docs/tutorial/data_modelling.py
+++ head/docs/tutorial/data_modelling.py
@@ -34,9 +34,9 @@
 
     @staticmethod
-    def Pickup(store: str) -> Literal["Delivery"]:
+    def Pickup(store: str) -> Delivery:
         return Delivery(pickup=store)
 
     @staticmethod
-    def Shipping(address: Address) -> Literal["Delivery"]:
+    def Shipping(address: Address) -> Delivery:
         return Delivery(shipping=address)
Expression — docs/tutorial/optional_values.py
--- base/docs/tutorial/optional_values.py
+++ head/docs/tutorial/optional_values.py
@@ -7,4 +7,12 @@
 error explanation.
 """
+def _soundness_check(_v, _t):
+    if not isinstance(_v, _t):
+        raise TypeError(
+            f"type soundness violation: expected {getattr(_t, '__name__', _t)}, "
+            f"got {type(_v).__name__}"
+        )
+    return _v
+
 class Optional:
     def __init__(self, value):
@@ -155,25 +163,4 @@
     return a == b
 
-def _parametric_is_lenient(value, alias, variances):
-    # the checked-cast form: a value that records no reification has no
-    # arguments to check, so the base class test is the whole guarantee. this is
-    # what keeps `[1, 2] cast list[int]` legal while still rejecting a value
-    # whose recorded arguments contradict the target
-    alias = _by_alias(getattr(alias, "__value__", alias))
-    origin = getattr(alias, "__origin__", alias)
-    if not isinstance(value, origin):
-        return False
-    if not _by_generic_args(value, origin):
-        return True
-    return _parametric_is(value, alias, variances)
-
-def _soundness_check(_v, _t):
-    if not isinstance(_v, _t):
-        raise TypeError(
-            f"type soundness violation: expected {getattr(_t, '__name__', _t)}, "
-            f"got {type(_v).__name__}"
-        )
-    return _v
-
 def _soundness_parametric(_v, _alias, _variances):
     _alias = _by_alias(_alias)
Expression — docs/tutorial/railway.py
--- base/docs/tutorial/railway.py
+++ head/docs/tutorial/railway.py
@@ -7,4 +7,12 @@
 need nested `if` statements or broad exception handling.
 """
+def _soundness_check(_v, _t):
+    if not isinstance(_v, _t):
+        raise TypeError(
+            f"type soundness violation: expected {getattr(_t, '__name__', _t)}, "
+            f"got {type(_v).__name__}"
+        )
+    return _v
+
 def _by_type_param_defaults(args):
     # a class records its generic bases *unsubstituted* — `class L[T = Never]
@@ -145,25 +153,4 @@
     return a == b
 
-def _parametric_is_lenient(value, alias, variances):
-    # the checked-cast form: a value that records no reification has no
-    # arguments to check, so the base class test is the whole guarantee. this is
-    # what keeps `[1, 2] cast list[int]` legal while still rejecting a value
-    # whose recorded arguments contradict the target
-    alias = _by_alias(getattr(alias, "__value__", alias))
-    origin = getattr(alias, "__origin__", alias)
-    if not isinstance(value, origin):
-        return False
-    if not _by_generic_args(value, origin):
-        return True
-    return _parametric_is(value, alias, variances)
-
-def _soundness_check(_v, _t):
-    if not isinstance(_v, _t):
-        raise TypeError(
-            f"type soundness violation: expected {getattr(_t, '__name__', _t)}, "
-            f"got {type(_v).__name__}"
-        )
-    return _v
-
 def _soundness_parametric(_v, _alias, _variances):
     _alias = _by_alias(_alias)
Expression — expression/_by_runtime.py
(only produced on head)
Expression — expression/collections/array.py
--- base/expression/collections/array.py
+++ head/expression/collections/array.py
@@ -9,187 +9,5 @@
 lazy from ty_extensions import JustFloat
 lazy from typing import Callable, Literal
-class Optional:
-    def __init__(self, value):
-        self.value = value
-
-    def __class_getitem__(cls, item):
-        return cls
-
-    def __repr__(self):
-        return f"Some({self.value!r})"
-
-def _by_type_param_defaults(args):
-    # a class records its generic bases *unsubstituted* — `class L[T = Never]
-    # (list[T])` stores `list[T]`, never `list[Never]` — so a type parameter
-    # left at its pep 696 default resolves to that default rather than staying a
-    # bare TypeVar that matches nothing
-    resolved = []
-    substituted = False
-    for arg in args:
-        has_default = getattr(arg, "has_default", None)
-        if has_default is not None and has_default():
-            resolved.append(arg.__default__)
-            substituted = True
-        else:
-            resolved.append(arg)
-    return tuple(resolved) if substituted else args
-
-def _by_alias(value):
... 6386 characters elided ...
 
 
@@ -343,5 +161,5 @@
             arr = array.array("f", arr)
             type_code = TypeCode.Float
-        elif (isinstance(arr0, float64) or isinstance(arr0, double)):
+        elif isinstance(arr0, float64 | double):
             arr = array.array("d", arr)
             type_code = TypeCode.Double
Expression — expression/collections/asyncseq.py
--- base/expression/collections/asyncseq.py
+++ head/expression/collections/asyncseq.py
@@ -1,15 +1,8 @@
-lazy from typing import Callable, Literal, overload
-def _soundness_check(_v, _t):
-    if not isinstance(_v, _t):
-        raise TypeError(
-            f"type soundness violation: expected {getattr(_t, '__name__', _t)}, "
-            f"got {type(_v).__name__}"
-        )
-    return _v
-
+lazy from typing import Any, Callable, overload
+from expression._by_runtime import _soundness_check
 lazy import builtins
 lazy import itertools
 lazy from collections.abc import AsyncIterable, AsyncIterator
-lazy from typing import Any, TypeVar, cast
+lazy from typing import TypeVar, cast
 
 lazy from expression.core import Option, pipe
@@ -28,5 +21,5 @@
         self._ai = ai
 
-    async def map(self, mapper: Callable[[TSource], TResult]) -> Literal["AsyncSeq[TResult]"]:
+    async def map(self, mapper: Callable[[TSource], TResult]) -> AsyncSeq[TResult]:
         # Use the module-level `map` function defined later to transform the
         # underlying async iterable and wrap the result back into an AsyncSeq.
... 1768 characters elided ...
@@ -240,5 +233,5 @@
         return builtins.max(items)
 
-    async def min(self: Literal["AsyncSeq[TSourceSortable]"]) -> TSourceSortable:
+    async def min(self: AsyncSeq[TSourceSortable]) -> TSourceSortable:
         """Return minimum of all elements."""
         items: list[TSourceSortable] = []
Expression — expression/collections/block.py
--- base/expression/collections/block.py
+++ head/expression/collections/block.py
@@ -19,188 +19,6 @@
 """
 lazy from typing import Any, Callable, Literal, overload
+from expression._by_runtime import Optional, _soundness_check, _soundness_parametric
 _MISSING = object()
-class Optional:
-    def __init__(self, value):
-        self.value = value
-
-    def __class_getitem__(cls, item):
-        return cls
-
-    def __repr__(self):
-        return f"Some({self.value!r})"
-
-def _by_type_param_defaults(args):
-    # a class records its generic bases *unsubstituted* — `class L[T = Never]
-    # (list[T])` stores `list[T]`, never `list[Never]` — so a type parameter
-    # left at its pep 696 default resolves to that default rather than staying a
-    # bare TypeVar that matches nothing
-    resolved = []
-    substituted = False
-    for arg in args:
-        has_default = getattr(arg, "has_default", None)
-        if has_default is not None and has_default():
-            resolved.append(arg.__default__)
-            substituted = True
-        else:
-            resolved.append(arg)
... 6084 characters elided ...
-            f"got {type(_v).__name__}"
-        )
-    if getattr(_v, "__orig_class__", None) is not None and not _parametric_is(_v, _alias, _variances):
-        raise TypeError(
-            f"type soundness violation: expected {_alias}, got {_v.__orig_class__}"
-        )
-    return _v
-
Expression — expression/collections/map.py
--- base/expression/collections/map.py
+++ head/expression/collections/map.py
@@ -1,15 +1,4 @@
 lazy from typing import Callable
-def _soundness_check(_v, _t):
-    if not isinstance(_v, _t):
-        raise TypeError(
-            f"type soundness violation: expected {getattr(_t, '__name__', _t)}, "
-            f"got {type(_v).__name__}"
-        )
-    return _v
-
-def _soundness_iter(_it, _t):
-    for _x in _it:
-        yield _soundness_check(_x, _t)
-
+from expression._by_runtime import _soundness_check, _soundness_iter
 # Attribution to original authors of this code
 # --------------------------------------------
Expression — expression/collections/maptree.py
--- base/expression/collections/maptree.py
+++ head/expression/collections/maptree.py
@@ -23,26 +23,5 @@
 """
 lazy from typing import Any, Callable
-class Optional:
-    def __init__(self, value):
-        self.value = value
-
-    def __class_getitem__(cls, item):
-        return cls
-
-    def __repr__(self):
-        return f"Some({self.value!r})"
-
-def _soundness_check(_v, _t):
-    if not isinstance(_v, _t):
-        raise TypeError(
-            f"type soundness violation: expected {getattr(_t, '__name__', _t)}, "
-            f"got {type(_v).__name__}"
-        )
-    return _v
-
-def _soundness_iter(_it, _t):
-    for _x in _it:
-        yield _soundness_check(_x, _t)
-
+from expression._by_runtime import Optional, _soundness_check, _soundness_iter
 
 lazy import builtins
Expression — expression/collections/seq.py
--- base/expression/collections/seq.py
+++ head/expression/collections/seq.py
@@ -23,188 +23,6 @@
 """
 lazy from typing import Any, Callable, overload
+from expression._by_runtime import Optional, _soundness_check, _soundness_parametric
 _MISSING = object()
-class Optional:
-    def __init__(self, value):
-        self.value = value
-
-    def __class_getitem__(cls, item):
-        return cls
-
-    def __repr__(self):
-        return f"Some({self.value!r})"
-
-def _by_type_param_defaults(args):
-    # a class records its generic bases *unsubstituted* — `class L[T = Never]
-    # (list[T])` stores `list[T]`, never `list[Never]` — so a type parameter
-    # left at its pep 696 default resolves to that default rather than staying a
-    # bare TypeVar that matches nothing
-    resolved = []
-    substituted = False
-    for arg in args:
-        has_default = getattr(arg, "has_default", None)
-        if has_default is not None and has_default():
-            resolved.append(arg.__default__)
-            substituted = True
-        else:
-            resolved.append(arg)
... 6084 characters elided ...
-            f"got {type(_v).__name__}"
-        )
-    if getattr(_v, "__orig_class__", None) is not None and not _parametric_is(_v, _alias, _variances):
-        raise TypeError(
-            f"type soundness violation: expected {_alias}, got {_v.__orig_class__}"
-        )
-    return _v
-
Expression — expression/core/aiotools.py
--- base/expression/core/aiotools.py
+++ head/expression/core/aiotools.py
@@ -9,12 +9,5 @@
 """
 lazy from typing import Any
-def _soundness_check(_v, _t):
-    if not isinstance(_v, _t):
-        raise TypeError(
-            f"type soundness violation: expected {getattr(_t, '__name__', _t)}, "
-            f"got {type(_v).__name__}"
-        )
-    return _v
-
+from expression._by_runtime import _soundness_check
 
 lazy import asyncio
Expression — expression/core/async_builder.py
--- base/expression/core/async_builder.py
+++ head/expression/core/async_builder.py
@@ -5,12 +5,5 @@
 """
 lazy from typing import Callable, Literal
-def _soundness_check(_v, _t):
-    if not isinstance(_v, _t):
-        raise TypeError(
-            f"type soundness violation: expected {getattr(_t, '__name__', _t)}, "
-            f"got {type(_v).__name__}"
-        )
-    return _v
-
+from expression._by_runtime import _soundness_check
 
 lazy import inspect
Expression — expression/core/builder.py
--- base/expression/core/builder.py
+++ head/expression/core/builder.py
@@ -1,11 +1,4 @@
 lazy from typing import Callable, Literal
-def _soundness_check(_v, _t):
-    if not isinstance(_v, _t):
-        raise TypeError(
-            f"type soundness violation: expected {getattr(_t, '__name__', _t)}, "
-            f"got {type(_v).__name__}"
-        )
-    return _v
-
+from expression._by_runtime import _soundness_check
 lazy import inspect
 lazy from abc import ABC
@@ -117,5 +110,5 @@
                 # maps to return_(value), a None return value maps to zero().
                 result_value = _soundness_check(cast(Literal["_T | None"], body), str)
-                if False:
+                if result_value is None:
                     return self.run(self.zero())
                 return self.run(self.return_(result_value))
Expression — expression/core/fn.py
--- base/expression/core/fn.py
+++ head/expression/core/fn.py
@@ -1,161 +1,3 @@
-def _by_type_param_defaults(args):
-    # a class records its generic bases *unsubstituted* — `class L[T = Never]
-    # (list[T])` stores `list[T]`, never `list[Never]` — so a type parameter
-    # left at its pep 696 default resolves to that default rather than staying a
-    # bare TypeVar that matches nothing
-    resolved = []
-    substituted = False
-    for arg in args:
-        has_default = getattr(arg, "has_default", None)
-        if has_default is not None and has_default():
-            resolved.append(arg.__default__)
-            substituted = True
-        else:
-            resolved.append(arg)
-    return tuple(resolved) if substituted else args
-
-def _by_alias(value):
-    # a reified generic class specializes to a *subclass*, which records the
-    # alias it stands for; anything else already is what it says it is. read
-    # from the class's own dict, so an ordinary subclass of a specialization is
-    # not mistaken for one
-    if isinstance(value, type):
... 5767 characters elided ...
 
@@ -213,5 +55,5 @@
 
     async def trampoline(bouncer: TailCallResult[_TResult, _P]) -> _TResult:
-        while _parametric_is(bouncer, TailCall, (0,)):
+        while isinstance(bouncer, TailCall):
             bouncer = _soundness_check(cast(TailCall[_P], bouncer), TailCall)
             args, kw = bouncer.args, bouncer.kw
Expression — expression/core/mailbox.py
--- base/expression/core/mailbox.py
+++ head/expression/core/mailbox.py
@@ -1,11 +1,4 @@
 lazy from typing import Any, Callable
-def _soundness_check(_v, _t):
-    if not isinstance(_v, _t):
-        raise TypeError(
-            f"type soundness violation: expected {getattr(_t, '__name__', _t)}, "
-            f"got {type(_v).__name__}"
-        )
-    return _v
-
+from expression._by_runtime import _soundness_check
 # Attribution to original authors of this code
 # --------------------------------------------
@@ -158,5 +151,5 @@
             self.continuation, cont = None, self.continuation
 
-            if True:  # type: ignore
+            if cont is not None:  # type: ignore
                 cont(msg)
Expression — expression/core/option.py
--- base/expression/core/option.py
+++ head/expression/core/option.py
@@ -7,24 +7,7 @@
 """
 lazy from typing import Callable, Literal, Protocol
-class Optional:
-    def __init__(self, value):
-        self.value = value
-
-    def __class_getitem__(cls, item):
-        return cls
-
-    def __repr__(self):
-        return f"Some({self.value!r})"
-
+from expression._by_runtime import Optional, _soundness_check
 class _Callable_3fc10be8(Protocol):
     def __call__(self, *args: "*_P") -> "_TResult": ...
-
-def _soundness_check(_v, _t):
-    if not isinstance(_v, _t):
-        raise TypeError(
-            f"type soundness violation: expected {getattr(_t, '__name__', _t)}, "
-            f"got {type(_v).__name__}"
-        )
-    return _v
Expression — expression/core/pipe.py
--- base/expression/core/pipe.py
+++ head/expression/core/pipe.py
@@ -13,14 +13,7 @@
 """
 lazy from typing import Callable, Protocol, overload
+from expression._by_runtime import _soundness_check
 class _Callable_22b0031f(Protocol):
     def __call__(self, *args: "*_Q") -> "_B": ...
-
-def _soundness_check(_v, _t):
-    if not isinstance(_v, _t):
-        raise TypeError(
-            f"type soundness violation: expected {getattr(_t, '__name__', _t)}, "
-            f"got {type(_v).__name__}"
-        )
-    return _v
Expression — expression/core/result.py
--- base/expression/core/result.py
+++ head/expression/core/result.py
@@ -10,22 +10,5 @@
 """
 lazy from typing import Callable, Literal
-class Optional:
-    def __init__(self, value):
-        self.value = value
-
-    def __class_getitem__(cls, item):
-        return cls
-
-    def __repr__(self):
-        return f"Some({self.value!r})"
-
-def _soundness_check(_v, _t):
-    if not isinstance(_v, _t):
-        raise TypeError(
-            f"type soundness violation: expected {getattr(_t, '__name__', _t)}, "
-            f"got {type(_v).__name__}"
-        )
-    return _v
-
+from expression._by_runtime import Optional, _soundness_check
Expression — expression/core/tagged_union.py
--- base/expression/core/tagged_union.py
+++ head/expression/core/tagged_union.py
@@ -1,11 +1,4 @@
 lazy from typing import Any, Callable, overload
-def _soundness_check(_v, _t):
-    if not isinstance(_v, _t):
-        raise TypeError(
-            f"type soundness violation: expected {getattr(_t, '__name__', _t)}, "
-            f"got {type(_v).__name__}"
-        )
-    return _v
-
+from expression._by_runtime import _soundness_check
 lazy from copy import deepcopy
 lazy from dataclasses import dataclass, field, fields
Expression — expression/core/typing.py
--- base/expression/core/typing.py
+++ head/expression/core/typing.py
@@ -91,5 +91,5 @@
     """
     origin: type[_Derived] | None = get_origin(type_) or type_
-    if True and isinstance(expr, origin):
+    if origin is not None and isinstance(expr, origin):
         return expr
Expression — expression/effect/async_option.py
--- base/expression/effect/async_option.py
+++ head/expression/effect/async_option.py
@@ -6,22 +6,5 @@
 """
 lazy from typing import Callable
-class Optional:
-    def __init__(self, value):
-        self.value = value
-
-    def __class_getitem__(cls, item):
-        return cls
-
-    def __repr__(self):
-        return f"Some({self.value!r})"
-
-def _soundness_check(_v, _t):
-    if not isinstance(_v, _t):
-        raise TypeError(
-            f"type soundness violation: expected {getattr(_t, '__name__', _t)}, "
-            f"got {type(_v).__name__}"
-        )
-    return _v
-
+from expression._by_runtime import Optional, _soundness_check
 
 lazy from collections.abc import AsyncGenerator, Awaitable, Callable
Expression — expression/effect/async_result.py
--- base/expression/effect/async_result.py
+++ head/expression/effect/async_result.py
@@ -6,12 +6,5 @@
 """
 lazy from typing import Callable
-def _soundness_check(_v, _t):
-    if not isinstance(_v, _t):
-        raise TypeError(
-            f"type soundness violation: expected {getattr(_t, '__name__', _t)}, "
-            f"got {type(_v).__name__}"
-        )
-    return _v
-
+from expression._by_runtime import _soundness_check
 
 lazy from collections.abc import AsyncGenerator, Awaitable, Callable
Expression — expression/effect/option.py
--- base/expression/effect/option.py
+++ head/expression/effect/option.py
@@ -1,21 +1,4 @@
 lazy from typing import Callable
-class Optional:
-    def __init__(self, value):
-        self.value = value
-
-    def __class_getitem__(cls, item):
-        return cls
-
-    def __repr__(self):
-        return f"Some({self.value!r})"
-
-def _soundness_check(_v, _t):
-    if not isinstance(_v, _t):
-        raise TypeError(
-            f"type soundness violation: expected {getattr(_t, '__name__', _t)}, "
-            f"got {type(_v).__name__}"
-        )
-    return _v
-
+from expression._by_runtime import Optional, _soundness_check
 lazy from collections.abc import Callable, Generator
 lazy from typing import Any, TypeVar
Expression — expression/effect/result.py
--- base/expression/effect/result.py
+++ head/expression/effect/result.py
@@ -1,11 +1,4 @@
 lazy from typing import Callable
-def _soundness_check(_v, _t):
-    if not isinstance(_v, _t):
-        raise TypeError(
-            f"type soundness violation: expected {getattr(_t, '__name__', _t)}, "
-            f"got {type(_v).__name__}"
-        )
-    return _v
-
+from expression._by_runtime import _soundness_check
 lazy from collections.abc import Callable, Generator
 lazy from typing import Any, TypeVar
Expression — expression/extra/option/pipeline.py
--- base/expression/extra/option/pipeline.py
+++ head/expression/extra/option/pipeline.py
@@ -1,21 +1,4 @@
 lazy from typing import Callable, overload
-class Optional:
-    def __init__(self, value):
-        self.value = value
-
-    def __class_getitem__(cls, item):
-        return cls
-
-    def __repr__(self):
-        return f"Some({self.value!r})"
-
-def _soundness_check(_v, _t):
-    if not isinstance(_v, _t):
-        raise TypeError(
-            f"type soundness violation: expected {getattr(_t, '__name__', _t)}, "
-            f"got {type(_v).__name__}"
-        )
-    return _v
-
+from expression._by_runtime import Optional, _soundness_check
 lazy from functools import reduce
 lazy from typing import Any, TypeVar
Expression — expression/extra/parser.py
--- base/expression/extra/parser.py
+++ head/expression/extra/parser.py
@@ -1,187 +1,5 @@
 lazy from ty_extensions import JustFloat
 lazy from typing import Any, Callable, overload
-class Optional:
-    def __init__(self, value):
-        self.value = value
-
-    def __class_getitem__(cls, item):
-        return cls
-
-    def __repr__(self):
-        return f"Some({self.value!r})"
-
-def _by_type_param_defaults(args):
-    # a class records its generic bases *unsubstituted* — `class L[T = Never]
-    # (list[T])` stores `list[T]`, never `list[Never]` — so a type parameter
-    # left at its pep 696 default resolves to that default rather than staying a
-    # bare TypeVar that matches nothing
-    resolved = []
-    substituted = False
-    for arg in args:
-        has_default = getattr(arg, "has_default", None)
-        if has_default is not None and has_default():
-            resolved.append(arg.__default__)
-            substituted = True
-        else:
-            resolved.append(arg)
-    return tuple(resolved) if substituted else args
-
-def _by_alias(value):
... 6161 characters elided ...
-        raise TypeError(
-            f"type soundness violation: expected {_alias}, got {_v.__orig_class__}"
-        )
-    return _v
-
+from expression._by_runtime import Optional, _soundness_check, _soundness_parametric
 
 lazy import string
Expression — expression/extra/result/catch.py
--- base/expression/extra/result/catch.py
+++ head/expression/extra/result/catch.py
@@ -1,11 +1,4 @@
 lazy from typing import Any, Callable, overload
-def _soundness_check(_v, _t):
-    if not isinstance(_v, _t):
-        raise TypeError(
-            f"type soundness violation: expected {getattr(_t, '__name__', _t)}, "
-            f"got {type(_v).__name__}"
-        )
-    return _v
-
+from expression._by_runtime import _soundness_check
 
 lazy from functools import wraps
Expression — expression/extra/result/pipeline.py
--- base/expression/extra/result/pipeline.py
+++ head/expression/extra/result/pipeline.py
@@ -1,11 +1,4 @@
 lazy from typing import Callable, overload
-def _soundness_check(_v, _t):
-    if not isinstance(_v, _t):
-        raise TypeError(
-            f"type soundness violation: expected {getattr(_t, '__name__', _t)}, "
-            f"got {type(_v).__name__}"
-        )
-    return _v
-
+from expression._by_runtime import _soundness_check
 lazy from functools import reduce
 lazy from typing import Any, TypeVar
Expression — expression/extra/result/traversable.py
--- base/expression/extra/result/traversable.py
+++ head/expression/extra/result/traversable.py
@@ -1,12 +1,5 @@
 """Data structures that can be traversed from left to right, performing an action on each element."""
 lazy from typing import Any, Callable
-def _soundness_check(_v, _t):
-    if not isinstance(_v, _t):
-        raise TypeError(
-            f"type soundness violation: expected {getattr(_t, '__name__', _t)}, "
-            f"got {type(_v).__name__}"
-        )
-    return _v
-
+from expression._by_runtime import _soundness_check
 
 lazy from typing import TypeVar
Expression — expression/system/disposable.py
--- base/expression/system/disposable.py
+++ head/expression/system/disposable.py
@@ -1,16 +1,5 @@
 lazy from abc import abstractmethod
 lazy from typing import Callable
-def _soundness_check(_v, _t):
-    if not isinstance(_v, _t):
-        raise TypeError(
-            f"type soundness violation: expected {getattr(_t, '__name__', _t)}, "
-            f"got {type(_v).__name__}"
-        )
-    return _v
-
-def _soundness_iter(_it, _t):
-    for _x in _it:
-        yield _soundness_check(_x, _t)
-
+from expression._by_runtime import _soundness_check, _soundness_iter
 
 lazy from abc import ABC
Expression — tests/_by_runtime.py
(only produced on head)
Expression — tests/test_array.py
--- base/tests/test_array.py
+++ head/tests/test_array.py
@@ -1,190 +1,4 @@
 lazy from typing import Callable
-class Optional:
-    def __init__(self, value):
-        self.value = value
-
-    def __class_getitem__(cls, item):
-        return cls
-
-    def __repr__(self):
-        return f"Some({self.value!r})"
-
-def _by_type_param_defaults(args):
-    # a class records its generic bases *unsubstituted* — `class L[T = Never]
-    # (list[T])` stores `list[T]`, never `list[Never]` — so a type parameter
-    # left at its pep 696 default resolves to that default rather than staying a
-    # bare TypeVar that matches nothing
-    resolved = []
-    substituted = False
-    for arg in args:
-        has_default = getattr(arg, "has_default", None)
-        if has_default is not None and has_default():
-            resolved.append(arg.__default__)
-            substituted = True
-        else:
-            resolved.append(arg)
-    return tuple(resolved) if substituted else args
-
-def _by_alias(value):
-    # a reified generic class specializes to a *subclass*, which records the
... 6176 characters elided ...
-        raise TypeError(
-            f"type soundness violation: expected {_alias}, got {_v.__orig_class__}"
-        )
-    return _v
-
+from tests._by_runtime import Optional, _soundness_check, _soundness_iter, _soundness_parametric
 lazy import functools
 lazy from collections.abc import Callable
Expression — tests/test_async_option_builder.py
--- base/tests/test_async_option_builder.py
+++ head/tests/test_async_option_builder.py
@@ -1,190 +1,4 @@
 """Tests for async_option builder implementation."""
-class Optional:
-    def __init__(self, value):
-        self.value = value
-
-    def __class_getitem__(cls, item):
-        return cls
-
-    def __repr__(self):
-        return f"Some({self.value!r})"
-
-def _by_type_param_defaults(args):
-    # a class records its generic bases *unsubstituted* — `class L[T = Never]
-    # (list[T])` stores `list[T]`, never `list[Never]` — so a type parameter
-    # left at its pep 696 default resolves to that default rather than staying a
-    # bare TypeVar that matches nothing
-    resolved = []
-    substituted = False
-    for arg in args:
-        has_default = getattr(arg, "has_default", None)
-        if has_default is not None and has_default():
-            resolved.append(arg.__default__)
-            substituted = True
-        else:
-            resolved.append(arg)
-    return tuple(resolved) if substituted else args
-
-def _by_alias(value):
... 6254 characters elided ...
-        raise TypeError(
-            f"type soundness violation: expected {_alias}, got {_v.__orig_class__}"
-        )
-    return _v
-
+from tests._by_runtime import Optional, _soundness_check, _soundness_iter, _soundness_parametric
 
 lazy import asyncio
Expression — tests/test_async_result_builder.py
--- base/tests/test_async_result_builder.py
+++ head/tests/test_async_result_builder.py
@@ -1,15 +1,4 @@
 """Tests for async_result builder implementation."""
-def _soundness_check(_v, _t):
-    if not isinstance(_v, _t):
-        raise TypeError(
-            f"type soundness violation: expected {getattr(_t, '__name__', _t)}, "
-            f"got {type(_v).__name__}"
-        )
-    return _v
-
-def _soundness_iter(_it, _t):
-    for _x in _it:
-        yield _soundness_check(_x, _t)
-
+from tests._by_runtime import _soundness_check, _soundness_iter
 
 lazy import asyncio
Expression — tests/test_asyncseq.py
--- base/tests/test_asyncseq.py
+++ head/tests/test_asyncseq.py
@@ -1,10 +1,3 @@
-def _soundness_check(_v, _t):
-    if not isinstance(_v, _t):
-        raise TypeError(
-            f"type soundness violation: expected {getattr(_t, '__name__', _t)}, "
-            f"got {type(_v).__name__}"
-        )
-    return _v
-
+from tests._by_runtime import _soundness_aiter, _soundness_check
 lazy import asyncio
 
@@ -31,5 +24,5 @@
 
         xs = AsyncSeq.range(count)
-        async for x in xs:
+        async for x in _soundness_aiter(xs, int):
             acc += x
 
@@ -45,5 +38,5 @@
         nonlocal acc
         xs = AsyncSeq.range(count)
-        async for x in xs:
+        async for x in _soundness_aiter(xs, int):
             acc += x
Expression — tests/test_block.py
--- base/tests/test_block.py
+++ head/tests/test_block.py
@@ -1,191 +1,5 @@
 lazy from ty_extensions import JustFloat
 lazy from typing import Callable
-class Optional:
-    def __init__(self, value):
-        self.value = value
-
-    def __class_getitem__(cls, item):
-        return cls
-
-    def __repr__(self):
-        return f"Some({self.value!r})"
-
-def _by_type_param_defaults(args):
-    # a class records its generic bases *unsubstituted* — `class L[T = Never]
-    # (list[T])` stores `list[T]`, never `list[Never]` — so a type parameter
-    # left at its pep 696 default resolves to that default rather than staying a
-    # bare TypeVar that matches nothing
-    resolved = []
-    substituted = False
-    for arg in args:
-        has_default = getattr(arg, "has_default", None)
-        if has_default is not None and has_default():
-            resolved.append(arg.__default__)
-            substituted = True
-        else:
-            resolved.append(arg)
-    return tuple(resolved) if substituted else args
-
-def _by_alias(value):
... 6254 characters elided ...
-        raise TypeError(
-            f"type soundness violation: expected {_alias}, got {_v.__orig_class__}"
-        )
-    return _v
-
+from tests._by_runtime import Optional, _soundness_check, _soundness_iter, _soundness_parametric
 lazy import functools
 lazy from builtins import list as list
Expression — tests/test_cancellation.py
--- base/tests/test_cancellation.py
+++ head/tests/test_cancellation.py
@@ -11,5 +11,5 @@
 def test_token_none_works():
     token = CancellationToken.none()
-    assert True
+    assert isinstance(token, CancellationToken)
     assert not token.can_be_canceled
     assert not token.is_cancellation_requested
@@ -22,10 +22,10 @@
 
     with source as disp:
-        assert True
+        assert isinstance(disp, Disposable)
 
 
 def test_token_cancelled_source_works():
     source = CancellationTokenSource.cancelled_source()
-    assert True
+    assert isinstance(source, CancellationTokenSource)
     assert source.is_cancellation_requested
Expression — tests/test_catch.py
--- base/tests/test_catch.py
+++ head/tests/test_catch.py
@@ -1,11 +1,4 @@
 lazy from typing import Any
-def _soundness_check(_v, _t):
-    if not isinstance(_v, _t):
-        raise TypeError(
-            f"type soundness violation: expected {getattr(_t, '__name__', _t)}, "
-            f"got {type(_v).__name__}"
-        )
-    return _v
-
+from tests._by_runtime import _soundness_check
 lazy from collections.abc import Generator
Expression — tests/test_curried.py
--- base/tests/test_curried.py
+++ head/tests/test_curried.py
@@ -1,15 +1,4 @@
 lazy from typing import Callable
-def _soundness_check(_v, _t):
-    if not isinstance(_v, _t):
-        raise TypeError(
-            f"type soundness violation: expected {getattr(_t, '__name__', _t)}, "
-            f"got {type(_v).__name__}"
-        )
-    return _v
-
-def _soundness_iter(_it, _t):
-    for _x in _it:
-        yield _soundness_check(_x, _t)
-
+from tests._by_runtime import _soundness_check, _soundness_iter
 
 lazy import pytest
Expression — tests/test_gen.py
--- base/tests/test_gen.py
+++ head/tests/test_gen.py
@@ -1,12 +1,5 @@
 """This file is just to explore how generators works
 """
-def _soundness_check(_v, _t):
-    if not isinstance(_v, _t):
-        raise TypeError(
-            f"type soundness violation: expected {getattr(_t, '__name__', _t)}, "
-            f"got {type(_v).__name__}"
-        )
-    return _v
-
+from tests._by_runtime import _soundness_check
 lazy from collections.abc import Generator
 
@@ -20,5 +13,5 @@
     gen = fn()
     value = next(gen)
-    assert True
+    assert value is None
 
 
@@ -29,5 +22,5 @@
     gen = fn()
     value = next(gen)
-    assert True
+    assert value is None
     with pytest.raises(StopIteration) as ex:
         next(gen)
Expression — tests/test_mailbox.py
--- base/tests/test_mailbox.py
+++ head/tests/test_mailbox.py
@@ -1,15 +1,4 @@
 lazy from typing import Callable
-def _soundness_check(_v, _t):
-    if not isinstance(_v, _t):
-        raise TypeError(
-            f"type soundness violation: expected {getattr(_t, '__name__', _t)}, "
-            f"got {type(_v).__name__}"
-        )
-    return _v
-
-def _soundness_iter(_it, _t):
-    for _x in _it:
-        yield _soundness_check(_x, _t)
-
+from tests._by_runtime import _soundness_check, _soundness_iter
 lazy import asyncio
Expression — tests/test_map.py
--- base/tests/test_map.py
+++ head/tests/test_map.py
@@ -1,190 +1,4 @@
 lazy from typing import Callable
-class Optional:
-    def __init__(self, value):
-        self.value = value
-
-    def __class_getitem__(cls, item):
-        return cls
-
-    def __repr__(self):
-        return f"Some({self.value!r})"
-
-def _by_type_param_defaults(args):
-    # a class records its generic bases *unsubstituted* — `class L[T = Never]
-    # (list[T])` stores `list[T]`, never `list[Never]` — so a type parameter
-    # left at its pep 696 default resolves to that default rather than staying a
-    # bare TypeVar that matches nothing
-    resolved = []
-    substituted = False
-    for arg in args:
-        has_default = getattr(arg, "has_default", None)
-        if has_default is not None and has_default():
-            resolved.append(arg.__default__)
-            substituted = True
-        else:
-            resolved.append(arg)
-    return tuple(resolved) if substituted else args
-
-def _by_alias(value):
-    # a reified generic class specializes to a *subclass*, which records the
... 6176 characters elided ...
-        raise TypeError(
-            f"type soundness violation: expected {_alias}, got {_v.__orig_class__}"
-        )
-    return _v
-
+from tests._by_runtime import Optional, _soundness_check, _soundness_iter, _soundness_parametric
 lazy from collections.abc import ItemsView, Iterable
Expression — tests/test_option.py
--- base/tests/test_option.py
+++ head/tests/test_option.py
@@ -1,191 +1,5 @@
 lazy from ty_extensions import JustFloat
 lazy from typing import Callable
-class Optional:
-    def __init__(self, value):
-        self.value = value
-
-    def __class_getitem__(cls, item):
-        return cls
-
-    def __repr__(self):
-        return f"Some({self.value!r})"
-
-def _by_type_param_defaults(args):
-    # a class records its generic bases *unsubstituted* — `class L[T = Never]
-    # (list[T])` stores `list[T]`, never `list[Never]` — so a type parameter
-    # left at its pep 696 default resolves to that default rather than staying a
-    # bare TypeVar that matches nothing
-    resolved = []
-    substituted = False
-    for arg in args:
-        has_default = getattr(arg, "has_default", None)
-        if has_default is not None and has_default():
-            resolved.append(arg.__default__)
-            substituted = True
-        else:
-            resolved.append(arg)
-    return tuple(resolved) if substituted else args
-
-def _by_alias(value):
... 6254 characters elided ...
-        raise TypeError(
-            f"type soundness violation: expected {_alias}, got {_v.__orig_class__}"
-        )
-    return _v
-
+from tests._by_runtime import Optional, _soundness_check, _soundness_iter, _soundness_parametric
 lazy from typing import Any, Annotated
Expression — tests/test_parser.py
--- base/tests/test_parser.py
+++ head/tests/test_parser.py
@@ -1,176 +1,4 @@
 lazy from typing import Any, Literal
-def _by_type_param_defaults(args):
-    # a class records its generic bases *unsubstituted* — `class L[T = Never]
-    # (list[T])` stores `list[T]`, never `list[Never]` — so a type parameter
-    # left at its pep 696 default resolves to that default rather than staying a
-    # bare TypeVar that matches nothing
-    resolved = []
-    substituted = False
-    for arg in args:
-        has_default = getattr(arg, "has_default", None)
-        if has_default is not None and has_default():
-            resolved.append(arg.__default__)
-            substituted = True
-        else:
-            resolved.append(arg)
-    return tuple(resolved) if substituted else args
-
-def _by_alias(value):
-    # a reified generic class specializes to a *subclass*, which records the
-    # alias it stands for; anything else already is what it says it is. read
-    # from the class's own dict, so an ordinary subclass of a specialization is
-    # not mistaken for one
-    if isinstance(value, type):
... 5863 characters elided ...
-        raise TypeError(
-            f"type soundness violation: expected {_alias}, got {_v.__orig_class__}"
-        )
-    return _v
-
+from tests._by_runtime import _soundness_check, _soundness_parametric
 
 lazy import string
Expression — tests/test_pipe.py
--- base/tests/test_pipe.py
+++ head/tests/test_pipe.py
@@ -1,11 +1,4 @@
 lazy from typing import Callable
-def _soundness_check(_v, _t):
-    if not isinstance(_v, _t):
-        raise TypeError(
-            f"type soundness violation: expected {getattr(_t, '__name__', _t)}, "
-            f"got {type(_v).__name__}"
-        )
-    return _v
-
+from tests._by_runtime import _soundness_check
 lazy from typing import TypeVar
Expression — tests/test_result.py
--- base/tests/test_result.py
+++ head/tests/test_result.py
@@ -1,191 +1,5 @@
 lazy from ty_extensions import JustFloat
 lazy from typing import Callable
-class Optional:
-    def __init__(self, value):
-        self.value = value
-
-    def __class_getitem__(cls, item):
-        return cls
-
-    def __repr__(self):
-        return f"Some({self.value!r})"
-
-def _by_type_param_defaults(args):
-    # a class records its generic bases *unsubstituted* — `class L[T = Never]
-    # (list[T])` stores `list[T]`, never `list[Never]` — so a type parameter
-    # left at its pep 696 default resolves to that default rather than staying a
-    # bare TypeVar that matches nothing
-    resolved = []
-    substituted = False
-    for arg in args:
-        has_default = getattr(arg, "has_default", None)
-        if has_default is not None and has_default():
-            resolved.append(arg.__default__)
-            substituted = True
-        else:
-            resolved.append(arg)
-    return tuple(resolved) if substituted else args
-
-def _by_alias(value):
... 6491 characters elided ...
 lazy from dataclasses import dataclass
 lazy from typing import Any, Annotated
@@ -258,6 +72,6 @@
 
     assert isinstance(xs, Result)
-    assert not xs.is_ok()
-    assert xs.is_error()
+    assert not _soundness_check(xs.is_ok(), bool)
+    assert _soundness_check(xs.is_error(), bool)
     assert str(xs) == f"Error {error}"
Expression — tests/test_seq.py
--- base/tests/test_seq.py
+++ head/tests/test_seq.py
@@ -1,190 +1,4 @@
 lazy from typing import Callable
-class Optional:
-    def __init__(self, value):
-        self.value = value
-
-    def __class_getitem__(cls, item):
-        return cls
-
-    def __repr__(self):
-        return f"Some({self.value!r})"
-
-def _by_type_param_defaults(args):
-    # a class records its generic bases *unsubstituted* — `class L[T = Never]
-    # (list[T])` stores `list[T]`, never `list[Never]` — so a type parameter
-    # left at its pep 696 default resolves to that default rather than staying a
-    # bare TypeVar that matches nothing
-    resolved = []
-    substituted = False
-    for arg in args:
-        has_default = getattr(arg, "has_default", None)
-        if has_default is not None and has_default():
-            resolved.append(arg.__default__)
-            substituted = True
-        else:
-            resolved.append(arg)
-    return tuple(resolved) if substituted else args
-
-def _by_alias(value):
-    # a reified generic class specializes to a *subclass*, which records the
... 6910 characters elided ...
+    assert [y for y in _soundness_iter(ys, int)] == [x + y for (x, y) in xs]
 
 
@@ -281,5 +95,5 @@
 
     assert isinstance(ys, Iterable)
-    assert [y for y in ys] == [x + y + z for (x, y, z) in xs]
+    assert [y for y in _soundness_iter(ys, int)] == [x + y + z for (x, y, z) in xs]
PyGithub — github/_by_runtime.py
(only produced on head)
PyGithub — openapi/_by_runtime.py
(only produced on head)
Tanjun — docs_src/usage.py
(only produced on head)

10985 finding(s) omitted to fit GitHub's 65536-character comment limit. Every finding, with nothing elided, is in the roundtrip-report.md artifact of this run.

@github-actions

github-actions Bot commented Sep 10, 2026

Copy link
Copy Markdown
Contributor

ecosystem check

Linter (stable)

✅ ecosystem check detected no linter changes.

Linter (preview)

✅ ecosystem check detected no linter changes.

Formatter (stable)

ℹ️ ecosystem check encountered format errors. (no format changes; 1 project error)

sphinx-doc/sphinx (error)

ruff format --no-preview --exclude tests/roots/test-pycode/cp_1251_coded.py

warning: Selection `DOC` has no effect because preview is not enabled.
warning: Detected debug build without --no-cache.
error: Encountered error: No such file or directory (os error 2)
error: Encountered error: No such file or directory (os error 2)
error: Encountered error: No such file or directory (os error 2)
error: Encountered error: No such file or directory (os error 2)
error: Encountered error: No such file or directory (os error 2)
error: Encountered error: No such file or directory (os error 2)
error: Encountered error: No such file or directory (os error 2)
error: Encountered error: No such file or directory (os error 2)

Formatter (preview)

✅ ecosystem check detected no format changes.

…ds, class variables and module-level variables

- `protected` joins `private` as a member modifier, an access from outside the
  class (or, for `protected`, outside its subclasses) is reported, and an
  override that narrows a member's visibility is rejected
- the modifiers work on class variables and module-level variables as well as
  methods, and the access check is gated on a cached pre-check
- a visibility keyword on a name that is part of a runtime interface is
  rejected, every binding and name list a keyword reaches is renamed, and
  properties follow the same rename rule
…n inlay hint showing that type

a property that carries an accessor block may leave its type out. the editor now
draws the type it resolves to where the declaration would have written it —
`let a⟨: 1⟩` for a `get() = 1` — under the `ty.inlayHints.propertyTypes` setting

`var c = 0` with an accessor block means `var c: int = 0`: the setter's `value`
is `int` and the getter must return one. before, the setter's unwritten
parameter opened an anonymous type parameter that leaked into storage, so the
property read as `int | value@c` and accepted anything. a property with no
initialiser (only a `let` can leave both out) takes its type from its getter,
and an initialiser on an explicit `field` still types the storage alone. an
initialiser on a computed property, which has no backing field to store it in,
was silently dropped and is now a parse error

the property-type and inferred-return hints skip a type ty never settled:
`Unknown`, and anything still carrying a cycle's divergence marker, which a
self-reading getter or `def f(): return f()` had been hinted as. a malformed
accessor, which recovers to an empty body, is not hinted either, and the
property hint is only emitted when the request covers the property's name

`redundant-return-annotation` no longer reports a property declared `None`: the
getter's return annotation is the property's type, not a `-> None` to remove

the getter is ranged onto its accessor rather than onto the declaration line.
`StmtFunctionDef::property_construct` answers whether a function is a property
getter and whether it is `static`, replacing the separate checks in the
extension and properties transforms and goto. a hand-written `@__property__` is
no longer taken for one — document symbols used to list it as a property

the transpiler took any accessor suite written on the accessor's own line for
the `get() = expr` form: `get(): pass` came out as the invalid `return pass`,
and `set(v): a = v; field = a` kept only its first statement, so the setter
never stored anything. the `=` form is now recognised only by the `return` the
parser synthesizes for it, and a same-line suite is emitted one statement per
line

the untyped shape is covered by the formatter fixture and by mdtests asserting
what a `get`-only type resolves to, one of which runs a same-line suite through
the divergence harness
… per package instead of pasted into every module

every helper the transpiled python calls was a rust string constant pasted into
the top of each module that used it, so a project carried the same few hundred
lines once per module and re-executed them once per module. a five-line module
came to ninety-seven lines, ninety of them the lazy-import polyfill

the helpers now live in `_by_runtime.py`, which `runtime.rs` slices by name: a
transform names the helpers the code it emits calls through typed `Helper`
constants, and what those in turn need is read out of their own bodies. the
helpers name their own imports rather than leaning on one the emitting module
happened to carry — `_by_loop_bind` was reading a `CellType` it never asked for.
the lazy-import polyfill, the optional wrapper, the discard adapter and the
match polyfill's helpers are all ordinary entries, and the constants and the
`wrapped_runtime` module they replaced are gone

a build stages `_by_runtime.py` inside each package it emits, and each module
imports the names it calls. inside the package rather than at the tree root,
because a root module would either not be packaged at all or claim a top-level
name a second basedpython wheel overwrites on install. a module in a directory
with no `__init__`, `by transpile` of one file, and `by transpile <dir>` still
paste the definitions in. the anon-named-tuple and inline-protocol preambles,
built as text after phase 0, make the same choice

- the lazy-import proxy's operator forwarding takes the class as a parameter, so
  a dependency closure keeps it with the proxy instead of dropping every
  operator
- `Character` keeps a `sys.modules` registry, since a pasted-in class is a class
  per module and identity is what `isinstance` tests
- the match polyfill's sequence types are looked up on first use rather than
  when the runtime loads
- a relative import resolves inside `_lazy_module` / `_lazy_attr`
- the runtime goes after the imports and before the hoisted class definitions,
  so a named tuple field typed `int??` finds `Optional` when the class is built
- the lazy-import pass keeps the runtime import eager, and `_lazy_module` is
  imported only where it is called
- `by compile` finishes its tree when staging the runtime fails
- `check_and_transpile` takes an `Emit` instead of ten arguments

phase 3 rejects output that calls one of the transpiler's own helpers without
having asked for it: forgetting to record the need produced python that parsed,
checked, and raised `NameError` the first time the lowered line ran, which
`_parametric_is_lenient` was doing. the check only blames the transpiler for
names the author never reads, needs them bound at module scope, counts a `case`
capture as a binding, and points at the call through its range

a built package is tested to run off its one copy, and packaging is documented
…untime guard read a reified type parameter's actual argument

`raises T` now reads as what a call solved `T` to: `f(TypeError())` on
`def f[T: BaseException](t: T) raises T` raises `TypeError`, not `T`. a
method's class type parameter is read through the receiver, and a parameter a
call leaves unsolved stands for its declared ceiling. a function type records
the specializations it went through, so `f[X]`, `Reader[K].read` and
classmethods specialize the clause too, and inference records each call's own
solution. a recursive call that solves its own type parameter to something else
is resolved rather than dropped, and a closure over an enclosing function's
parameter no longer reports `BaseException`

a type parameter with no exception bound is rejected in a clause, which is what
makes its ceiling an exception set. `invalid-raises-clause` checks only the
set's own members, and says why. the override check compares against the base
as the subclass specializes it

a `raises T` runtime guard on a reified function reads `T` from the
specialization the call went through, and on a reified class's method from the
receiver, so `rethrow[FileNotFoundError](...)` rejects a `PermissionError` its
`OSError` bound would let through. an unreified parameter stays on its ceiling:
asking for its argument would mean reifying it, and turning a check on must not
change how the program is built. a subscripted argument is tested by its
origin, and the guard lands below a statement another lowering puts before its
`def`

the guard keeps a reified generic subscriptable — it wrapped the `generic` in a
plain function, so `f[int](...)` failed with `'function' object is not
subscriptable` whenever the guard was on

the pep 695 polyfill writes its `TypeVar` definitions through the
statement-insert channel. they are statements, and as an ordinary text edit
another lowering's decorator at the same offset could land above them — the
guard on a generic `def` below 3.12 put a `TypeVar` assignment between the
decorator and its `def`, which is not python
`def f()` compiled and ran. the lowering fills the missing body in with `: ...`,
so what the program got was a function that returns `None` standing where the
implementation was meant to be, and nothing said so: `empty-body` only speaks when
the declared return type rules `None` out, which leaves `def f()` and
`def f() -> None` silent. the return type is beside the point anyway — the body is
what went missing.

`missing-function-body` reports a `def` written with no body at all wherever the
position asks for an implementation. a stub file, a protocol member, an
`abstract def` or `@abstractmethod`, an overload declaration — written `@overload`
or as a run of same-name `def`s — and an `if TYPE_CHECKING` block each ask for a
declaration and are untouched. so is an `init(...)`, whose body is built from the
attribute parameters it declares, and so is every other construct the parser builds
a function out of: an accessor block, a trailing-lambda block. an empty body on one
of those means the source failed to parse, which has been reported already.

`empty-body` no longer speaks for the bodyless form at all. it is about a body that
is there and returns `None` where it should not, and saying that of a `def` with no
body describes the consequence rather than the problem.

a `decorator def` is not exempt. the dispatcher its lowering writes calls the body
the source is supposed to supply and wrote `...` in its place, so
`decorator def route(fn)` in a module that runs produced a decorator handing back
`None`.

ty synthesises a loop-header definition for every place a loop carries round, and a
`def` in a loop body binds its name through one. `is_implicit_overload` counted that
as another `def` of the same name, so a single stub-shaped `def` in a loop read as a
member of an overload group — a position that declares — and every bodyless `def` in
a loop body went unreported, `while True:` included. loop headers are skipped now,
which loses nothing: every real same-name `def` is in the same list of bindings, which
is what keeps an overload run written inside a loop working.

`by transpile --reverse` rewrote every `def f(): ...` to a bodyless `def f()`, which
is now reported wherever the position needs an implementation — and the pass has no
way to tell those positions apart. bodyless is the stub idiom, so a stub is where it
is written now; outside one the body the author wrote stays, which is valid
basedpython either way and transpiles back to the python it came from. an empty
`class` still loses its body everywhere: a class with no members is a whole class.
the fixtures that used `: ...` as filler while testing another reverse transform
carry it through to their output now.
`alignment_groups` only reported a run whose members shared an `=` column
when one of them also carried two or more spaces before it, on the grounds
that a column arrived at by coincidence of name length was never aligned on
purpose. but a reader cannot tell the two apart:

    a = 1 + 1
    b = True or False

those `=` are in one column, and hints of unequal width (`a: Literal[2]`,
`b: Literal[True]`) take that column apart exactly as they take a hand-padded
one apart. requiring the padding meant the commonest shape of all — short
names, one space each — was left ragged, which is what this was for

so the shared column is the whole of the test, and the padding a member
happens to carry goes back to being what it always was: room the client
spends before the line has to grow. `gap()` had no caller left once the check
went, so its sentence moves to the field it describes

two cases the wider rule newly reaches are pinned: an unpadded column, and a
member with no gap at all (`ab=f()`), which the client has to take rather
than drop — a group is sized against every member at once
…dencies ty_server gained

82f8b57 added `rand` and `ty_static` to `ty_server` and regenerated only the
root lock. `crates/basedpython` is a workspace of its own, and `Build binaries`
runs maturin `--locked` against its lock, so every platform job failed at
`cargo metadata`. the missing entries are added without changing any version
… and make the `manual_isinstance` fix unsafe

a basedpython `is` is a type test, and one the value's static type settles is
emitted as its answer. python's `is None` and `isinstance` run whatever the
annotations say, so reversing them into `is` tests let the forward pass fold
them away: `assert x is None` came back as `assert True`,
`assert f() is None` on an `f` annotated `-> int` as the always-failing
`assert (f(), False)[1]`, and an `if not isinstance(x, int): raise` guard on a
parameter annotated `int` as `if False:`

every python `is` / `is not` now reverses to `===` / `!==`, `None` included,
and an `isinstance` call stays a call. `manual_isinstance` still suggests `is`,
but its fix is unsafe: the two agree only where the annotations hold at runtime
…d reverse python's string annotations to the expressions they spell

a basedpython annotation is checked as deferred, so `def f() -> Later` above
`class Later` checks clean, but before 3.14 python evaluates the annotation as
the `def` runs and raises `NameError`. the transpiler only quoted a class's own
name, so a later class, a method naming one, and a name imported only under
`if TYPE_CHECKING:` all crashed at import on those targets

`auto_quote` now asks ty, through `is_forward_reference`, whether each name in
an annotation python evaluates as its definition runs (parameters, returns,
class-body and module-level variables) is bound by that point, with a binding
made only under `if TYPE_CHECKING:` not counting. a name the program binds but
not by then makes the whole annotation quoted, as one wrapper template, so the
lowerings inside it land between the quotes. bases and value-position
subscripts keep quoting the class's own name where it stands. `v: P = ...`
above `P = ...` was such a crash, and is quoted now

the driver ranks a template that only wraps its span ahead of a substitution of
the same span, so the wrapper claims it: a quote around `(Tag) -> None` holds
the `Callable[[Tag], None]` the callable lowering writes as text

the reverse left a python string annotation in place, which basedpython reads
as a literal type: `-> "Plain"` came back as `-> Literal["Plain"]`. every
string in an annotation position, `Literal` arguments and `Annotated` metadata
aside, now becomes the expression it spells before the other reverse
transforms run, so `"Plain | None"` reaches the optional transform and becomes
`Plain?`
@KotlinIsland
KotlinIsland merged commit e317fa7 into main Sep 11, 2026
83 of 85 checks passed
@KotlinIsland
KotlinIsland deleted the fixes-and-features branch September 11, 2026 10:14
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant