Skip to content

Commit

Permalink
fix(common): pattern() factory should construct a CoercedTo(type)
Browse files Browse the repository at this point in the history
… pattern from coercible types
  • Loading branch information
kszucs committed Aug 11, 2023
1 parent 0ffda75 commit 09be2cd
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 5 deletions.
10 changes: 5 additions & 5 deletions ibis/common/patterns.py
Original file line number Diff line number Diff line change
Expand Up @@ -659,7 +659,7 @@ class Namespace:
InstanceOf(type=<class 'ibis.expr.operations.numeric.Negate'>)
>>>
>>> ns.Negate(5)
Object(type=InstanceOf(type=<class 'ibis.expr.operations.numeric.Negate'>), args=(EqualTo(value=5),), kwargs=FrozenDict({}))
Object(type=CoercedTo(target=<class 'ibis.expr.operations.numeric.Negate'>), args=(EqualTo(value=5),), kwargs=FrozenDict({}))
"""

__slots__ = ("module", "pattern")
Expand Down Expand Up @@ -930,9 +930,6 @@ def match(self, value, context):
else:
return NoMatch

def __repr__(self):
return f"CoercedTo({self.target.__name__!r})"


As = CoercedTo

Expand Down Expand Up @@ -1596,7 +1593,10 @@ def pattern(obj: AnyType) -> Pattern:
elif isinstance(obj, Mapping):
return PatternMapping(obj)
elif isinstance(obj, type):
return InstanceOf(obj)
if issubclass(obj, Coercible):
return CoercedTo(obj)
else:
return InstanceOf(obj)
elif get_origin(obj):
return Pattern.from_typehint(obj)
elif is_iterable(obj):
Expand Down
6 changes: 6 additions & 0 deletions ibis/common/tests/test_patterns.py
Original file line number Diff line number Diff line change
Expand Up @@ -976,9 +976,15 @@ def test_pattern_coercible_sequence_type():


def test_pattern_function():
class MyNegativeInt(int, Coercible):
@classmethod
def __coerce__(cls, other):
return cls(-int(other))

assert pattern(...) == Any()
assert pattern(Any()) == Any()
assert pattern(int) == InstanceOf(int)
assert pattern(MyNegativeInt) == CoercedTo(MyNegativeInt)
assert pattern(List[int]) == ListOf(InstanceOf(int))
assert pattern([int, str, 1]) == PatternSequence(
[InstanceOf(int), InstanceOf(str), EqualTo(1)]
Expand Down

0 comments on commit 09be2cd

Please sign in to comment.