Python style switches. Showing several ways of making a 'switch' in python.
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 | #==================================================
# 1. Select non-function values:
#==================================================
location = 'myHome'
fileLocation = {'myHome' :path1,
'myOffice' :path2,
'somewhere':path3}[location]
#==================================================
# 2. Select functions:
#==================================================
functionName = input('Enter a function name')
eval('%s()'% functionName )
#==================================================
# 3. Select values with 'range comparisons':
#==================================================
#
# Say, we have a range of values, like: [0,1,2,3]. You want to get a
# specific value when x falls into a specific range:
#
# x<0 : 'return None'
# 0<=x<1: 'return 1'
# 1<=x<2: 'return 2'
# 2<=x<3: 'return 3'
# 3<=x : 'return None'
#
# It is eazy to construct a switch by simply making the above rules
# into a dictionary:
selector={
x<0 : 'return None',
0<=x<1 : 'return 1',
1<=x<2 : 'return 2',
2<=x<3 : 'return 3',
3<=x : 'return None'
}[1]
# During the construction of the selector, any given x will turn the
# selector into a 2-element dictionary:
selector={
0 : 'return None',
1 : #(return something you want),
}[1]
# This is very useful in places where a selection is to be made upon any
# true/false decision. One more example:
selector={
type(x)==str : "it's a str",
type(x)==tuple: "it's a tuple",
type(x)==dict : "it's a dict"
} [1]
#==================================================
# 4. Select functions with 'range comparisons':
#==================================================
#
# You want to execute a specific function when x falls into a specific range:
functionName={
x<0 : 'setup',
0<=x<1: 'loadFiles',
1<=x<2: 'importModules'
}[1]
eval('%s()'% functionName )
|
Be careful when selecting functions using the 'dictionary-based' switches :
If it is constructed this way:
aFunction={ xBe careful when selecting functions using the 'dictionary-based' switches :
If it is constructed this way:
aFunction={ x
Tags: shortcuts
double posting.
double posting.