Reputation: 8659
Let's say you have 10 variables, one of which will be true and the others will be false. Other than having a ton of if/elif statements, is there a better way to find which variable is true and then do "something" based on which variable was true? Each "something" will be different depending on which variable is true.
Upvotes: 2
Views: 240
Reputation: 184280
bools = [False, False, False, True, False]
# we're using constants here but you can use variables
# find first True value
whichbool = bools.index(True)
# now call a function based on that value
[func0, func1, func2, func3, func4][whichbool]()
If there is any possibility that there might be no True
value, or more than one, you may want to check for this. The easiest way to check for both situations is to use the sum()
function. True
is 1 as an integer, so if you get any sum other than 1, there are too few or not enough True
values in the list.
Upvotes: 4
Reputation: 375784
Any time you have a number of variables, and you want to pick among them based on a condition, you should consider using a dict instead.
bools['a'] = False
bools['b'] = False
bools['c'] = True
for k, v in bools.iteritems():
if v:
print "The true variable is", k
With the name of the variable in hand, you can invoke functions by name:
class MyHandlers(object):
def a_is_true(self):
# do something because of a
def b_is_true(self):
# do something because of b
handler = MyHandlers()
handler.getattr(k + "_is_true")()
Upvotes: 0
Reputation: 48028
Yes, there is. It'd be something like this:
def func1():
print "function 1"
def func2():
print "function 2"
def func3():
print "function 3"
lookup = {'val1': func1, 'val2': func2, 'val3': func3}
toCall = 'val2'
lookup[toCall]()
This would allow you to retrieve and call a function based on the value of a variable. Not quite identical to the other answer, but extremely similar. This is a standard approach to emulating the switch
statement from other languages.
Upvotes: 1
Reputation: 500703
First off, you could store the values in a list rather than in separate variables:
l = [v1, v2, v3, v4, v5, v6, v7, v8, v9, v10]
print l.index(True)
This will print 0
if v1
is true, 1
if v2
is true and so on.
This doesn't, however, solve the question of how to handle different behaviours for different variables. If you find if
-elif
-...
objectionable, you could have a parallel list of functions to be called for each of the ten cases.
fns = [f1, f2, f3, f4, f5, f6, f7, f8, f9, f10]
fns[l.index(True)]() # call the appropriate function
Whether this can be considered an improvement over having a ton of elif
blocks really depends on the amount of code associated with f1
...f10
.
Upvotes: 1