forked from tadzik/switch4python
-
Notifications
You must be signed in to change notification settings - Fork 1
/
switch.py
43 lines (31 loc) · 856 Bytes
/
switch.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
__all__ = ['switch']
from contextlib import contextmanager
from typing import (
cast,
Callable,
Generator,
Generic,
TypeVar,
Union,
)
T = TypeVar('T')
GuardT = Callable[[T], bool]
class Case(Generic[T]):
def __init__(self, value: T):
self.value = value
self.finished = False
def __call__(self, cond: Union[T, GuardT]) -> bool:
if (self.finished
or (hasattr(cond, '__call__')
and not cast(GuardT, cond)(self.value))
or cond != self.value):
return False
self.finished = True
return True
def fallthrough(self) -> None:
self.finished = False
def default(self) -> bool:
return not self.finished
@contextmanager
def switch(value: T) -> Generator[Case[T], None, None]:
yield Case(value)