-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpts-1.py
85 lines (61 loc) · 1.86 KB
/
pts-1.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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
# Python Thougts Snippets #1
# python 3.7
# 2019-08-15
# plost: https://pythonicthoughtssnippets.github.io/#1-dictionaries-for-control-flow
# THIS CODE IS NOT MEANT TO BE FUNCTIONAL OR EXECUTABLE,
# IT IS A REPRESENTATION OF AN IDEA AND AN EXAMPLE
# TO RAISE DISCUSSION
def translate_ifs(val):
if isinstance(val, str):
return val
elif isinstance(val, int):
return str(val)
elif bool(val is False):
return 'F'
elif bool(val is True):
return 'T'
else:
raise SomeError('My control Flow Error!')
# evaluates WITHOUT else statement
def translate_1(val):
d = {
isinstance(val, str): val,
isinstance(val, int): str(val),
bool(val is False): 'F',
bool(val is True): 'T',
}
try:
return d[True]
except IndexError:
pass # handle exception here
# evaluates WITH else statement
def translate_2(val):
d = {
True: 'Happy Flowers!',
isinstance(val, str): val,
isinstance(val, int): str(val),
bool(val is False): 'F',
bool(val is True): 'T',
}
return d[True]
# Because functions in Pyhon are first class objects...
def translate_3(val):
d = {
True: func1,
isinstance(val, str): func2,
isinstance(val, int): func3,
bool(val is False): func4,
bool(val is True): func5,
}
return d[True](val)
# # you can even use partials to prepare function calls
def translate_4(val):
from functools import partial
d = {
True: partial(func1, some_val),
isinstance(val, str): partial(func2, some_val),
isinstance(val, int): partial(func3, some_val),
bool(val is False): partial(func4, some_val),
bool(val is True): partial(func5, some_val),
}
return d[True]()