Choosing a function randomly

Posted on

Question :

Choosing a function randomly

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()]


The code above seems to execute all 3 functions, not just the randomly chosen one. What’s the correct way to do this?

Answer #1:

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.

Answered By: Ned Batchelder

Answer #2:

from random import choice

#Step 1: define some functions
def foo(): 

def bar():

def baz():

#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 ;-)

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():

def bar():

def baz():

random_function = my_picker()
result_of_random_function = random_function()
Answered By: mgilson

Answer #3:

Almost — try this instead:

from random import choice
random_function_selector = [foo, foobar, fudge]


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.

Answered By: Peter

Answer #4:

  1. Generate a random integer up to how many elements you have
  2. Call a function depending on this number

import random

choice = random.randomint(0,3)
if choice == 0:
elif choice == 1:
Answered By: aw4lly

Answer #5:

One straightforward way:

# generate a random int between 0 and your number of functions - 1
x = random.choice(range(num_functions))
if (x < 1):
elif (x < 2):
# etc
elif (x < number of functions):
Answered By: mfrankli

Leave a Reply

Your email address will not be published. Required fields are marked *