Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Store functions in list and call them later

I want to store functions in a list and then later in a program call those functions from that list.

This works for me, however, I don't know if it is correct :

#example functions, my functions would actually get user input etc.
def func1():
    return 2
def func2():
    return 3

options = [ func1, func2 ]

#call functions

options[0]()

Is this the proper way to store functions in a list and call it ? Or is there a different, better way to do this?

like image 943
Davlog Avatar asked Dec 14 '14 18:12

Davlog


2 Answers

Yes, you can do it. If you want to call all functions in the list with a "one liner" you can do the following:

results = [f() for f in options]
like image 183
code monkey Avatar answered Sep 27 '22 21:09

code monkey


Yes, this is correct, though if your functions are really one-liner in nature, I would suggest you also have a look at lambdas, so that your entire code can be reduced to:

options = [lambda: 3, lambda: 2]

As already pointed out in comments, you will Of course need to remember the order of the functions in the list.

like image 27
Anshul Goyal Avatar answered Sep 27 '22 20:09

Anshul Goyal