Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Choosing a function randomly

Tags:

python

random

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?

like image 616
S3pHiRoTh Avatar asked Jan 04 '13 03:01

S3pHiRoTh


1 Answers

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.

like image 92
Ned Batchelder Avatar answered Oct 02 '22 18:10

Ned Batchelder