Skip to content

Commit

Permalink
Sketch for nicer-looking notation of cases as methods
Browse files Browse the repository at this point in the history
  • Loading branch information
jacob414 committed Nov 19, 2020
1 parent 5350d49 commit 46dd5a8
Showing 1 changed file with 15 additions and 2 deletions.
17 changes: 15 additions & 2 deletions kingston/match.py
Original file line number Diff line number Diff line change
Expand Up @@ -171,7 +171,8 @@ class Matcher(dict, Generic[MatchArgT, MatchRetT]):
concrete instances of matchers you implement.
"""
def signature(self, handler: Callable) -> Sequence: # pragma: nocov
@staticmethod
def signature(handler: Callable) -> Sequence: # pragma: nocov
...

def callsign(self, args: Sequence[MatchArgT],
Expand Down Expand Up @@ -206,6 +207,12 @@ def invoke(self, handler: Callable, args: Sequence, kwargs: Mapping):
*box(unbox(args)), **kwargs)

def __call__(self, *args: Any, **kwargs: Any) -> MatchRetT:
for cb, deco_case in ((getattr(self, name), getattr(self,
name).__case__)
for name in dir(self)
if hasattr(getattr(self, name), '__case__')):
self[deco_case] = cb

try:
return self.invoke(self.match(args, kwargs), args, kwargs)
except KeyError:
Expand Down Expand Up @@ -251,7 +258,8 @@ class TypeMatcher(Matcher):
'str'
>>>
"""
def signature(self, handler: Callable) -> Sequence:
@staticmethod
def signature(handler: Callable) -> Sequence:
return cast(Sequence, unbox(primparams(handler)))

def callsign(self, args: Sequence[MatchArgT],
Expand Down Expand Up @@ -297,3 +305,8 @@ def wrap(handler, *xparams, **xopts):
return handler

return wrap


def case(func: Callable, getsig=TypeMatcher.signature) -> Callable:
func.__case__ = getsig(func)[1:]
return func

0 comments on commit 46dd5a8

Please sign in to comment.