0

I'm trying to use the random.sample function in Python (specifically, Psychopy) to randomly sample from a list of functions. Here is my code:

from psychopy import visual, core, event, gui
import random
import string

win = visual.Window([800,600], monitor="testMonitor", units = "pix", color="white",fullscr=False)    

def test1():
    welcome = "blah1"
    welcometext = visual.TextStim(win, text=welcome, wrapWidth=500, color="black")
    welcometext.draw()
    win.flip()
    event.waitKeys()

def test2():
    welcome = "blah2"
    welcometext = visual.TextStim(win, text=welcome, wrapWidth=500, color="black")
    welcometext.draw()
    win.flip()
    event.waitKeys()

def test3():
    welcome = "blah3"
    welcometext = visual.TextStim(win, text=welcome, wrapWidth=500, color="black")
    welcometext.draw()
    win.flip()
    event.waitKeys()

mylist = [test1, test2, test3]
random_sample = random.sample(mylist,1)()

When I try to run this code I get:

TypeError: 'list' object is not callable

I'm a bit lost as to why the random.sample doesn't work here, so any help would be very much appreciated. Also, as a side note, if I change the last bit of code to use random.choice, then this function seems to work perfectly fine:

mylist = [test1, test2, test3]
random_choice = random.choice(mylist)()
Jonas Lindeløv
  • 5,442
  • 6
  • 31
  • 54

2 Answers2

2

Try:

random_sample = random.sample(mylist, 1)[0]()

random.sample returns a list, so you may pick the first element and call it as a function.

Christian Tapia
  • 33,620
  • 7
  • 56
  • 73
0

As noted in a comment above:

random_sample = random.sample(mylist,1)()

That last () is calling the return of random.sample(mylist,1).

It is equivalent to writing:

random_sample = random.sample(mylist,1)
random_sample = random_sample()

Since random_sample at this point is referring to a list, it is not callable.

You need to call the element inside the list, rather than the list, so this should read:

random_sample = random.sample(mylist,1)[0]()
selllikesybok
  • 1,250
  • 11
  • 17