Passing functions around and executing

Patrick Mullen saluk64007 at gmail.com
Wed May 14 21:26:51 EDT 2008


Here's a quick dumb example, hope it helps:

def function1(a,b,c):
   print a,b,c
def function2(x):
   print x
def function3(y):
   print y+3

def executeall(list):
   print "setting up"
   for function,args in list:
      function(*args)   #Calls the function passing in the arguments

mylist = [[function1,(1,2,3)],[function2,("green",)],[function3,(5.5,)]]
executeall(mylist)

---------
The hard part is the fact that you mentioned some arguments need to be
passed in, some of the time.  This kind of situation makes the most sense if
all of the functions take the same arguments (or no arguments).  Then you
could just do this:
--------------------
def function1():
   print 1
def function2():
   print 2
def function3():
   print 3

def executeall(list):
   print "setting up"
   for function in list:
      function()

mylist = [function1,function2,function3]
executeall(mylist)
--------------------------
So you see, treating functions as regular objects and passing them around,
is as easy as not putting the call operator (parenthesis) to the right of
the function name.

print function   #Prints the representation of the function object
print function()  #Calls the function and then prints what the function
returns

Hope it helps.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20080514/4eecfa97/attachment-0001.html>


More information about the Python-list mailing list