Skip to content
This repository has been archived by the owner on Oct 4, 2024. It is now read-only.

add support for _ default key #35

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
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
17 changes: 12 additions & 5 deletions adt/decorator.py
Original file line number Diff line number Diff line change
Expand Up @@ -123,17 +123,24 @@ def match(self: Any,
caseNames = _cases.__members__.keys()
upperKeys = {k: k.upper() for k in kwargs.keys()}

unmatched = set(caseNames) - set(upperKeys.values())
if "_" in upperKeys.values():
for key in unmatched:
kwargs[key] = kwargs["_"]
upperKeys[key] = key
del upperKeys["_"]
del kwargs["_"]
elif unmatched:
raise ValueError(
f"Incomplete pattern match against {self} (missing {unmatched})"
)

for key in upperKeys.values():
if key not in caseNames:
raise ValueError(
f'Unrecognized case {key} in pattern match against {self} (expected one of {caseNames})'
)

for key in caseNames:
if key not in upperKeys.values():
raise ValueError(
f'Incomplete pattern match against {self} (missing {key})')

for key, callback in kwargs.items():
upperKey = upperKeys[key]

Expand Down
21 changes: 21 additions & 0 deletions tests/test_either.py
Original file line number Diff line number Diff line change
Expand Up @@ -89,3 +89,24 @@ def test_accessorsConsistentWithMatching(self, e: Either[_L, _R]) -> None:
self.assertEqual(
e.left(),
e.match(left=lambda x: x, right=helpers.invalidPatternMatch))

@given(from_type(Either))
def test_matching_with_default_key(self, e: Either[_L, _R]) -> None:
if e.match(left=lambda _: True, right=lambda _: False):
self.assertEqual(
e.left(),
e.match(right=helpers.invalidPatternMatch, _=lambda x: x))
self.assertEqual(
e.left(),
e.match(_=helpers.invalidPatternMatch, left=lambda x: x))
else:
self.assertEqual(
e.right(),
e.match(_=helpers.invalidPatternMatch, right=lambda x: x))

self.assertEqual(
e.right(),
e.match(left=helpers.invalidPatternMatch, _=lambda x: x))

with self.assertRaises(ValueError):
e.match(foobar=lambda x: x, _=lambda x: x) # type: ignore