Skip to content

Commit 7da8e53

Browse files
committed
Adds ability to capture return value from the cases.
1 parent 5f18697 commit 7da8e53

File tree

2 files changed

+30
-2
lines changed

2 files changed

+30
-2
lines changed

switchlang.py

Lines changed: 15 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,15 @@
11
# Here is a first pass implementation at adding switch
2+
import uuid
23
from typing import Callable, Any
34

45

56
class switch:
7+
__no_result = uuid.uuid4()
8+
69
def __init__(self, value):
710
self.value = value
811
self.cases = {}
12+
self.__result = switch.__no_result
913

1014
def default(self, func: Callable[[], Any]):
1115
self.case('__default__', func)
@@ -42,6 +46,15 @@ def __exit__(self, exc_type, exc_val, exc_tb):
4246
func = self.cases.get('__default__')
4347

4448
if not func:
45-
raise Exception("Value does not match any case and there is no default case: value {}".format(self.value))
49+
raise Exception("Value does not match any case and there "
50+
"is no default case: value {}".format(self.value))
51+
52+
# noinspection PyCallingNonCallable
53+
self.__result = func()
54+
55+
@property
56+
def result(self):
57+
if self.__result == switch.__no_result:
58+
raise Exception("No result has been computed.")
4659

47-
func()
60+
return self.__result

tests/coretests.py

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -132,3 +132,18 @@ def get_set_case(val):
132132
s.default(lambda: get_set_case('default'))
133133

134134
self.assertEqual(executed_case, "even")
135+
136+
def test_return_value_from_case(self):
137+
value = 4
138+
with switch(value) as s:
139+
s.case([1, 3, 5, 7], lambda: value + 1)
140+
s.case([0, 2, 4, 6, 8], lambda: value * value)
141+
s.default(lambda: 0)
142+
143+
self.assertEqual(s.result, 16)
144+
145+
# noinspection PyStatementEffect
146+
def test_result_inaccessible_if_hasnt_run(self):
147+
with self.assertRaises(Exception):
148+
s = switch(7)
149+
s.result

0 commit comments

Comments
 (0)