Petr Jakes wrote: > I have got names of functions stored in the file. For the simplicity > expect one row only with two function names: printFoo, printFOO > In my code I would like to define functions and then to read function > names from the file, so the functions can be executed in the order the > function names are stored in a file.
Somehow, when people invent little languages like you are doing now, the languages tend to grow over time...until you realize that you should have written the scripts in Python... It's all up to you of course, but making your code contain proper Python code might be something to consider. Little languages are sometimes useful. [EMAIL PROTECTED] wrote: > functions = ("printFoo", "printFOO") # list or tuple of strings from > file, or wherever > for function in functions: > call = function + "()" > eval(call) I wouldn't do this. eval has security issues, and it's overkill for simply finding names in a namespace as you saw in the other replies. Kent Johnson wrote: > If the functions are in the same module as the calling code: > functions=('printFoo', 'printFOO') > for function in functions: > globals()[function]() and Larry Bates wrote (slightly corrected): > Create dictionary with the function names as keys and the pointer to > function definition as value: > > fdict={'printFoo': printFoo, 'printFOO': printFOO} > functions=('printFoo', 'printFOO') > for function in functions: > if fdict.has_key(function): fdict[function]() > else: > print "No function named=%s defined" % function These two options are basically the same. The difference is that Kent suggest that you use a mapping of names to functions provided by Python, while Larry suggests that you make one yourself. (BTW, instead of globals() you might want locals() depending on what scope your functions are defined in.) While Kent's suggestion is a little less work, Larry's suggestion buys you some more benfits: - You can use other names than the actual function names as keys in the dict. This means that: -You can use reserved words (in, while etc) in your little script -You can rename functions and reorganize your code without breaking your scripts. -You can have command names in your script that contain national characters, spaces, punctuation, start with digits, etc (won't, stop!, 1st time, 1.2.45.start etc). - It's safer: You control exactly what functions the script might call. Those who write code you run eval on can basically get arbitrary code executed. $ cat > evil.py print "Gotcha" $ python [snip] >>> def x(): print 'Ok' ... >>> eval('x'+'()') Ok >>> eval('__import__("evil") and x'+'()') Gotcha Ok If you want more than just function names in your minilanguage, you might want to have a look at the shlex module. -- http://mail.python.org/mailman/listinfo/python-list