Is there a way to choose a function randomly?
Example:
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?
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.
Almost -- try this instead:
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 withchoice
, and call it.import random
One straightforward way:
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...):