Is there a way to choose a function randomly?
from random import choice def foo(): ... def foobar(): ... def fudge(): ... random_function_selector = [foo(), foobar(), fudge()] print(choice(random_function_selector))
The code above seems to execute all 3 functions, not just the randomly chosen one. What’s the correct way to do this?
from random import choice random_function_selector = [foo, foobar, fudge] print choice(random_function_selector)()
Python functions are first-class objects: you can refer to them by name without calling them, and then invoke them later.
In your original code, you were invoking all three, then choosing randomly among the results. Here we choose a function randomly, then invoke it.
from random import choice #Step 1: define some functions def foo(): pass def bar(): pass def baz(): pass #Step 2: pack your functions into a list. # **DO NOT CALL THEM HERE**, if you call them here, #(as you have in your example) you'll be randomly #selecting from the *return values* of the functions funcs = [foo,bar,baz] #Step 3: choose one at random (and call it) random_func = choice(funcs) random_func() #<-- call your random function #Step 4: ... The hypothetical function name should be clear enough ;-) smile(reason=your_task_is_completed)
Just for fun:
Note that if you really want to define the list of function choices before you actually define the functions, you can do that with an additional layer of indirection (although I do NOT recommend it — there’s no advantage to doing it this way as far as I can see…):
def my_picker(): return choice([foo,bar,baz]) def foo(): pass def bar(): pass def baz(): pass random_function = my_picker() result_of_random_function = random_function()
Almost — try this instead:
from random import choice random_function_selector = [foo, foobar, fudge] print(choice(random_function_selector)())
This assigns the functions themselves into the
random_function_selector list, rather than the results of calling those functions. You then get a random function with
choice, and call it.
- Generate a random integer up to how many elements you have
- Call a function depending on this number
choice = random.randomint(0,3) if choice == 0: foo() elif choice == 1: foobar() else: fudge()
One straightforward way:
# generate a random int between 0 and your number of functions - 1 x = random.choice(range(num_functions)) if (x < 1): function1() elif (x < 2): function2() # etc elif (x < number of functions): function_num_of_functions()