forked from mikeckennedy/python-switch
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathswitchlang.py
More file actions
47 lines (35 loc) · 1.27 KB
/
Copy pathswitchlang.py
File metadata and controls
47 lines (35 loc) · 1.27 KB
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
44
45
46
47
# Here is a first pass implementation at adding switch
from typing import Callable, Any
class switch:
def __init__(self, value):
self.value = value
self.cases = {}
def default(self, func: Callable[[], Any]):
self.case('__default__', func)
def case(self, key, func: Callable[[], Any]):
if isinstance(key, range):
for n in range(key.start, key.stop + 1, key.step):
self.case(n, func)
return
if isinstance(key, list):
for i in key:
self.case(i, func)
return
if key in self.cases:
raise ValueError("Duplicate case: {}".format(key))
if not func:
raise ValueError("Action for case cannot be None.")
if not callable(func):
raise ValueError("Func must be callable.")
self.cases[key] = func
def __enter__(self):
return self
def __exit__(self, exc_type, exc_val, exc_tb):
if exc_val:
raise exc_val
func = self.cases.get(self.value)
if not func:
func = self.cases.get('__default__')
if not func:
raise Exception("Value does not match any case and there is no default case: value {}".format(self.value))
func()