newbie-ish question on exec statement

Jeff Shannon jeff at ccvcorp.com
Thu Mar 14 14:18:27 EST 2002


Gabe Newcomb wrote:

> Hi all:
>         I'd appreciate any comments people might have on the limitations
> of using exec. Specifically, what I want to do is build function names
> dynamically and call them (don't ask why).

Okay, I won't ask why.  I'll just suggest another approach.  (Wanting to
dynamically select functions at runtime isn't odd or unusual; doing it with
exec is.)

Instead of calling function names via exec/eval(), build a dictionary of
function objects.

def my_func1(val1, val2 = "", val3 = ""):
    print "In func1"

def my_func2(val1, val2 = "", val3 = ""):
    print "In func2"

funcs = { "func1": my_func1, "func2": my_func2 }

funcname = raw_input("Which function to call?")
try:
    funcs[funcname](param)
except KeyError:
    print "No such function!"

You can dynamically add and remove functions from your dictionary, you can
test to see if they're present before trying to use them if you wish (with
the haskey() method), you can easily dynamically generate the funcname to
look for, and many other benefits, all without resorting to the mess of
using exec/eval().  (As a general rule of thumb, any time you're using exec
or eval(), there's probably an easier/cleaner/better way of doing whatever
it is you're doing.)

Jeff Shannon
Technician/Programmer
Credit International





More information about the Python-list mailing list