Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions docs/reference/core.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,3 +16,19 @@ Use the detailed module pages for all members: {doc}`Option <option>`,
{doc}`Result <result>`, {doc}`Try <try>`, {doc}`Pipe <pipe>`,
{doc}`Compose <compose>`, {doc}`Curry <curry>`, {doc}`Tagged unions <union>`, and
{doc}`Miscellaneous helpers <misc>`.

## Casting helpers

`upcast(Base, value)` and `downcast(Derived, value)` return the original object
after checking it with `isinstance`; they do not convert it. Incompatible values
raise `TypeError`, including when Python runs with optimization (`-O`).
`try_downcast(Derived, value)` returns `None` for an incompatible value.

The target determines the return type, but the uncurried `upcast` API does not
statically enforce the inheritance relationship. A curried form is planned for
the next major release so the target can be fixed before checking the value.

Targets must support `isinstance`. Parameterized generics such as `list[int]`
and `list[Any]` raise `TypeError` in all three helpers. In particular,
`try_downcast` no longer erases generic arguments and checks only the origin:
that could incorrectly present a list of strings as `list[int]`.
48 changes: 27 additions & 21 deletions expression/core/typing.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

from abc import abstractmethod
from collections.abc import Iterable
from typing import Any, Protocol, get_origin
from typing import Any, Protocol


class SupportsLessThan(Protocol):
Expand Down Expand Up @@ -52,39 +52,45 @@ class ModelField:
def validate(self, value: Any, values: dict[str, str], loc: str) -> tuple[Any, Any]: ...


def upcast[Base](type: type[Base], expr: Base) -> Base:
"""Upcast expression from a `Derived` to `Base`.
# TODO: In the next major Expression release, use upcast(Base)(value) so the
# target type is fixed before checking the value, allowing static rejection
# of invalid upcasts. Keep the uncurried API for compatibility in this release.
def upcast[Base](type: type[Base], expr: object) -> Base:
"""View a value as the requested base type without converting it.

Note: F# `:>` or `upcast`.
The target alone determines the return type. Python's type inference
cannot enforce the widening relationship in this two-argument API,
so compatibility is checked at runtime using `downcast`. A mismatch
raises `TypeError`, including under `python -O`.

Targets must support `isinstance`; parameterized generics are unsupported.
"""
return expr
return downcast(type, expr)


def downcast[Derived](type: type[Derived], expr: object) -> Derived:
"""Downcast expression `Derived` to `Base`.
"""Narrow a value to the requested runtime type without converting it.

Checks at compile time that the type of expression Base is a
supertype of Derived, and checks at runtime that Base is in fact an
instance of Derived.
Return the original value if it is an instance of the target type;
otherwise raise `TypeError`. The check remains active under `python -O`.
The source and target inheritance relationship is not checked statically.

Note: F# `:?>` or `downcast`.
Targets must support `isinstance`. Parameterized generics such as
`list[int]` are unsupported and raise `TypeError`.
"""
assert isinstance(expr, type), f"The type of expression {expr} is not a supertype of {type}"
return expr
if isinstance(expr, type):
return expr
raise TypeError(f"Cannot cast value to {type!r}: incompatible runtime type")


def try_downcast[Derived](type_: type[Derived], expr: object) -> Derived | None:
"""Downcast expression `Base` to `Derived`.

Check that the `Derived` type is a supertype of `Base`.

NOTE: Supports generic types.
"""Return the original value if it matches the target type, or `None`.

Returns:
None if `Derived` is not a supertype of `Base`.
Targets follow the same `isinstance` rules as `downcast`. Unsupported
targets, including parameterized generics, raise `TypeError` rather
than being treated as a value mismatch. Generic arguments are not erased.
"""
origin: type[Derived] | None = get_origin(type_) or type_
if origin is not None and isinstance(expr, origin):
if isinstance(expr, type_):
return expr

return None
Expand Down
71 changes: 53 additions & 18 deletions tests/test_typing.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
from typing import Any, cast
import subprocess
import sys
from typing import Any, assert_type, cast

import pytest

Expand All @@ -25,19 +27,17 @@ def test_upcast():
b = upcast(Base, d)

# Assert
assert isinstance(b, Base)
assert isinstance(b, Derived)
assert b is d
assert_type(b, Base)


def test_upcast_negative():
# Arrange
d = Derived()

# Act / Assert
x = upcast(Other, d)

with pytest.raises(AssertionError):
assert isinstance(x, Other)
with pytest.raises(TypeError, match="incompatible runtime type"):
upcast(Other, d)


def test_downcast():
Expand All @@ -48,19 +48,17 @@ def test_downcast():
d = downcast(Derived, b)

# Assert
assert isinstance(d, Base)
assert isinstance(d, Derived)
assert d is b
assert_type(d, Derived)


def test_downcast_negative():
# Arrange
b = cast(Base, Derived())

# Act / Assert
try:
with pytest.raises(TypeError, match="incompatible runtime type"):
downcast(Other, b)
except AssertionError:
pass


def test_try_downcast():
Expand All @@ -71,7 +69,8 @@ def test_try_downcast():
c = try_downcast(Derived, b)

# Assert
assert isinstance(c, Derived)
assert c is b
assert_type(c, Derived | None)


def test_try_downcast_negative():
Expand All @@ -85,15 +84,13 @@ def test_try_downcast_negative():
assert c is None


def test_try_cast_generic():
def test_try_cast_parameterized_generic_is_unsupported():
# Arrange
d: list[Derived] = [Derived()]

# Act
b = try_downcast(list[Any], d)

# Assert
assert isinstance(b, list)
with pytest.raises(TypeError):
try_downcast(list[Any], d)


def test_try_cast_generic_negative():
Expand All @@ -105,3 +102,41 @@ def test_try_cast_generic_negative():

# Assert
assert b is None


def test_parameterized_downcasts_reject_unchecked_element_types():
values: object = ["wrong"]
with pytest.raises(TypeError):
downcast(list[int], values)
with pytest.raises(TypeError):
try_downcast(list[int], values)


def test_cast_checks_survive_optimization():
script = """
from expression import downcast, upcast
for cast_value in (downcast, upcast):
try:
cast_value(int, "wrong")
except TypeError:
pass
else:
raise RuntimeError("Invalid cast succeeded under optimization")
"""
subprocess.run([sys.executable, "-O", "-c", script], check=True, capture_output=True, text=True)


def test_downcast_accepts_subclasses_and_preserves_identity():
value = Derived()
assert downcast(Base, value) is value
assert try_downcast(Base, value) is value


def test_upcast_rejects_invalid_narrowing():
with pytest.raises(TypeError):
upcast(Derived, Base())


def test_upcast_rejects_parameterized_target():
with pytest.raises(TypeError):
upcast(list[int], [1])
14 changes: 14 additions & 0 deletions tests/typing_contracts.py
Original file line number Diff line number Diff line change
Expand Up @@ -267,3 +267,17 @@ def as_float(value: int) -> float:
assert_type(values[:], MutableSequence[int])
values[0] = 3
values[:] = [4, 5]


def downcast_contract(value: object) -> None:
from expression import downcast, try_downcast

assert_type(downcast(str, value), str)
assert_type(try_downcast(str, value), str | None)


def upcast_target_contract(value: object) -> None:
from expression import upcast

assert_type(upcast(str, value), str)
assert_type(upcast(object, "value"), object)
22 changes: 21 additions & 1 deletion typing_tests/negative.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,21 @@
from collections.abc import Awaitable, Callable
from typing import Generic, Literal, TypeAlias, TypeVar, final

from expression import Error, MailboxProcessor, Nothing, Option, Result, Some, TaggedUnion, apipe, case, tag
from expression import (
Error,
MailboxProcessor,
Nothing,
Option,
Result,
Some,
TaggedUnion,
apipe,
case,
downcast,
tag,
try_downcast,
upcast,
)
from expression.collections import Block, Map, TypedArray
from expression.extra import async_result
from expression.extra.result import catch
Expand Down Expand Up @@ -169,3 +183,9 @@ def catch_source(value: int, *, suffix: str) -> str:
integers[:] = ["wrong"] # type-error
integers["wrong"] # type-error
Block([1]).sum_by(str) # type-error


# Cast targets must be types, not instances.
downcast(42, object()) # type-error
try_downcast(42, object()) # type-error
upcast(42, object()) # type-error
Loading