Odd behavior when randomly choosing function from list and testing which function it was

StackOverflow https://stackoverflow.com/questions/23449055

  •  14-07-2023
  •  | 
  •  

Question

Suppose I have these two functions:

def f1():
    pass

def f2():
    pass

If I want to run one of these two functions at random, I can do this:

flist = (f1, f2)
function = random.choice(flist)()

Unfortunatley, when I want to test which function it was using an if statement...

if function == f1:
    print "Good"

Good is not outputted. Why?

Was it helpful?

Solution

As roippi commented, your two blocks of code store different values in var. In the first version, you're storing the function you've chosen in var (and when you call it with var(), you discard the return value). In the second block, you call the function immediately after choosing it, and var gets assigned the function's return value (which probably makes your comparisons against the functions not useful).

The second block of code is equivalent to this modified version of the first block:

list_thing = [function1, function2]
var = random.choice(list_thing)
var2 = var()              # call the chosen function, and save its return value  as var2
if var2 == function1:     # compare against var2, rather than var here
    #Do something
elif var2 == function2:   # here too
    #Do something else

Unless your functions may return themselves (or each other), the second version of the code is probably not what you want. Without knowing what the functions do, or what your #Do something blocks mean, it's not easy to say what you should do. An alternative, I suppose would be to wrap up the function call along with the # something in another function, then make your choice between the wrapper functions:

def function1_and_something():
    function1()
    #Do something

def function2_and_something_else():
    function2()
    #Do something else

random.choice([function1_and_something, function2_and_something_else])() # chose and call

OTHER TIPS

Without knowing what the functions are or exactly what you want to do I have just made them strings to illustrate how to use random.choice and compare values.

import random
list_thing = ["function1", "function2"]
var = random.choice(list_thing)
if var == "function1":
    print "var is equal function1"
elif var == "function2":
    print "var is equal to function12"
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top