'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?



Solution 1:[1]

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]

Solution 2:[2]

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.

Solution 3:[3]

I like to do things like

class Commander:
    def CommandERROR(*args,**kwargs):
       print "Invalid command"
    def CommandFunc1(*args,**kwargs):
       print "Do Command 1"
    def CommandFunc2(*args,**kwargs):
       print "Do Command 2"
    def CallCommand(command,*args,**kwargs):
       self.__dict__.get("Command"+command,self.CommandError)(*args,**kwargs)


cmd = Commander()
cmd.CallCommand("Func1","arg1",something=5)
cmd.CallCommand("Func2","arg2",something=12)
cmd.CallCommand("Nothing","arg1",something=5)

as pointed out in the comments you can also put this in its own file to create the namespace and ommit the class ... although if you need to affect state then maybe a class is a better option ... you could also use a simple dict

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 code monkey
Solution 2
Solution 3