3

For example, when I have:

def function(text):
  print(text)

mylist = [function('yes'),function('no')]

mylist[0]

It just prints yes and no and doesn't do anything with mylist[0].

I want it to be able to call the function with parameters in the list and not have the functions run when the program starts. Is this possible?

user10993788
  • 51
  • 2
  • 5
  • Yes in Python functions are [first-class citizens](https://en.wikipedia.org/wiki/First-class_citizen) objects so you can stored them in a list. – Dani Mesejo Dec 06 '19 at 23:16
  • 1
    Does this answer your question? [Store functions in list and call them later](https://stackoverflow.com/questions/27472704/store-functions-in-list-and-call-them-later) – Brydenr Dec 06 '19 at 23:21
  • Almost. I'm really trying to store the parameters as well without making multiple functions and calling it on the spot. Thanks though. – user10993788 Dec 06 '19 at 23:24

3 Answers3

12

It sounds like you want to store the functions pre-bound with parameters. You can use functools.partial to give you a function with some or all of the parameters already defined:

from functools import partial

def f(text):
    print(text)

mylist = [partial(f, 'yes'), partial(f,'no')]

mylist[0]()
# yes

mylist[1]()
# no 
Mark
  • 90,562
  • 7
  • 108
  • 148
1

You can store functions as parameters, since functions in python are treated as first class citizens, which means you can effectively use them / treat them as you would a variable.

In your case, it isn't working because you're calling the function, not referencing the function.

mylist = [functionA,functionB]

mylist[0]('yes')

Here I've stored the references of the funcitons into a list, instead of calling them.

When you use (), you're effectively calling the function on the spot.

alex067
  • 3,159
  • 1
  • 11
  • 17
  • Is there another way to store the parameters without making multiple functions? I'm on the verge using strings and eval(). I'm trying to get something more like this: `mylist = [functionA('hi'),functionA('bye'),functionB('hi'),functionB('bye')] mylist[0]` – user10993788 Dec 06 '19 at 23:22
0

If you print mylist you will see that it contains None, which is the default return value of functions that don't have a return statement. You are, in fact, simply calling your function and saving the return value in a list.

sammy
  • 857
  • 5
  • 13