Skip to content Skip to sidebar Skip to footer

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

Solution 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:

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:

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


Solution 4:

Not sure how others do it, but I do it the same way. It's perfect for my basic codes, hence I believe they can be used elsewhere too.


Post a Comment for "Store Functions In List And Call Them Later"