Skip to content

Commit 5bbf065

Browse files
committed
Why not dicts?
1 parent 7da8e53 commit 5bbf065

File tree

1 file changed

+66
-0
lines changed

1 file changed

+66
-0
lines changed

README.md

Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -72,4 +72,70 @@ So that would be inconsistent.
7272

7373
Thoughts? I'm going with `1,2,3,4,5` for `range(1,5)` for now.
7474

75+
## Why not just raw `dict`?
7576

77+
The biggest push back on this idea is that we already have this problem solved.
78+
You write the following code.
79+
80+
```python
81+
switch = {
82+
1: method_on_one,
83+
2: method_on_two,
84+
3, method_on_three
85+
}
86+
87+
result = switch.get(value, defult_method_to_run)()
88+
```
89+
90+
This works but is very low on the functionality level. We have a better solution here
91+
I believe. Let's take this example and see how it looks in python-switch vs raw dicts:
92+
93+
```python
94+
# with python-switch:
95+
96+
while True:
97+
action = get_action(action)
98+
99+
with switch(action) as s:
100+
s.case(['c', 'a'], create_account)
101+
s.case('l', log_into_account)
102+
s.case('r', register_cage)
103+
s.case('u', update_availability)
104+
s.case(['v', 'b'], view_bookings)
105+
s.case('x', exit_app)
106+
s.case('', lambda: None)
107+
s.case(range(1,6), lambda: set_level(action))
108+
s.default(unknown_command)
109+
110+
result = s.result
111+
```
112+
113+
Now compare that to they espoused *pythonic* way:
114+
115+
```python
116+
# with raw dicts
117+
118+
while True:
119+
action = get_action(action)
120+
121+
switch = {
122+
'c': create_account,
123+
'a': create_account,
124+
'l': log_into_account,
125+
'r': register_cage,
126+
'u': update_availability,
127+
'v': view_bookings,
128+
'b': view_bookings,
129+
'x': exit_app,
130+
1: lambda: set_level(action),
131+
2: lambda: set_level(action),
132+
3: lambda: set_level(action),
133+
4: lambda: set_level(action),
134+
5: lambda: set_level(action),
135+
'': lambda: None,
136+
}
137+
result = switch.get(action, unknown_command)()
138+
```
139+
140+
Personally, I much prefer to read and write the on above. That's why I wrote this module.
141+
It seems to convey the intent of swtich way more than the dict. But either are options.

0 commit comments

Comments
 (0)