Skip to content

Commit

Permalink
feat(builders): support coercion from Builder and Deferred instances
Browse files Browse the repository at this point in the history
  • Loading branch information
kszucs committed Sep 10, 2024
1 parent 1867b40 commit 2a846fe
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 3 deletions.
5 changes: 2 additions & 3 deletions koerce/builders.py
Original file line number Diff line number Diff line change
Expand Up @@ -152,13 +152,12 @@ def __rxor__(self, other: Any) -> Deferred:

@cython.cclass
class Builder:
# TODO(kszucs): cover with tests
@staticmethod
def __coerce__(value):
def __coerce__(value) -> Builder:
if isinstance(value, Builder):
return value
elif isinstance(value, Deferred):
return value._builder
return cython.cast(Deferred, value)._builder
else:
raise ValueError(f"Cannot coerce {type(value).__name__!r} to Builder")

Expand Down
8 changes: 8 additions & 0 deletions koerce/tests/test_builders.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
Item,
Just,
Map,
Builder,
Seq,
Unop,
Var,
Expand Down Expand Up @@ -510,3 +511,10 @@ def test_deferred_is_not_truthy(obj):
TypeError, match="The truth value of Deferred objects is not defined"
):
bool(obj)


def test_builder_coercion():
assert Builder.__coerce__(Deferred(Var("a"))) == Var("a")
assert Builder.__coerce__(Var("a")) == Var("a")
with pytest.raises(ValueError):
Builder.__coerce__(1)

0 comments on commit 2a846fe

Please sign in to comment.