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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With