forked from tadzik/switch4python
- Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathswitch.py
More file actions
Latest commit
43 lines (31 loc) · 856 Bytes
/
Copy pathswitch.py
File metadata and controls
43 lines (31 loc) · 856 Bytes
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']
fromcontextlibimportcontextmanager
fromtypingimport (
cast,
Callable,
Generator,
Generic,
TypeVar,
Union,
)
T=TypeVar('T')
GuardT=Callable[[T], bool]
classCase(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__')
andnotcast(GuardT, cond)(self.value))
orcond!=self.value):
returnFalse
self.finished=True
returnTrue
deffallthrough(self) ->None:
self.finished=False
defdefault(self) ->bool:
returnnotself.finished
@contextmanager
defswitch(value: T) ->Generator[Case[T], None, None]:
yieldCase(value)