Executing functions

Ethan Furman ethan at stoneleaf.us
Fri Feb 11 09:47:37 EST 2011


DataSmash wrote:
> Can someone help me understand why Example #1 & Example #2 will run
> the functions,
> while Example #3 DOES NOT?
> Thanks for your time!
> R.D.
> 
> def One():
>     print "running fuction 1"
> def Two():
>     print "running fuction 2"
> def Three():
>     print "running fuction 3"
> 
> 
> # Example #1
> fList = ["Two()","Three()"]
> for func in fList:
>     exec func

In this case, func is set to the strings 'Two()' and 'Three()', then the 
<exec func> line tells Python to evaluate the strings and execute them. 
  While this style can be useful, it is also *much* slower than example 
2; if all you want is to cycle through the functions, a better way is:

--> fList = [Two, Three]
--> for func in fList:
-->     func()


> # Example #2
> Two()
> Three()

The functions Two and Three are called directly


> # Example #2 <-- should be 3  :)
> fList = ["Two()","Three()"]
> for func in fList:
>     func

This is not calling func (no () at the end), and in fact doesn't do 
anything if called as a script besides evaluate func -- it's a string, 
but not being assigned anywhere, so unless you are running from the 
interactive prompt where it will be echoed to screen, nothing happens.

~Ethan~



More information about the Python-list mailing list