Calling functions in a loop

Peter Hansen peter at engcorp.com
Sat Jul 14 20:32:54 CEST 2001


NANDYALA D Gangadhar wrote:
> I am new to Python (I already like it very much) and I have a newbee
> question: How do I call a set of functions from inside a loop? I tried
> the following, and it understandably fails with:
[...]
> Would someone show the correct way of getting the functionality I need?

There is not necessarily a "correct" way (and we aren't sure what
you really need).

You could use:

functionList = ['f1', 'f2']

def f1():  print 'f1'
def f2():  print 'f2'

if __name__ == '__main__':
    for func in functionList:
        if locals().has_key(func):
            locals()[func]()

This retrieves the function objects by name from the local namespace
and calls them.  (locals() returns a dictionary, the variable in 
square brackets selects an item from the dictionary, and the
parentheses cause the object to be called.)

A perhaps "better" approach is to put references to the functions
directly in the list:

functionList = [f1, f2]

if __name__ == '__main__':
    for func in functionList:
        func()

Now you have to make sure functionList is created _after_ the 
functions.

By the way, you probably should not use a name like __all__.  
Names starting and ending with double underscores
should be reserved for the system, not used in your own code.

In this case, __all__ has already been used in Python 2.1 for 
a list of names that should be imported from a module when the
module is imported with a "from module import *" statement.
If you weren't trying to use it for that purpose, avoid __all__.

-- 
----------------------
Peter Hansen, P.Eng.
peter at engcorp.com



More information about the Python-list mailing list