views:

42

answers:

1

All,

foo.py

def foo_001(para): tmp = para + 2 return tmp 
def foo_002(para): tmp = para * 2 return tmp 
def foo_003(para): tmp = para / 2 return tmp 

... 
def foo_100(para): tmp = #complex algo, return tmp 

main.py

from foo import * 
fun_name = ["foo_001","foo_002","foo_002" ... "foo_100"] 

src = 1 
rzt = []  
for i in fun_name: 
    rzt.extent(eval(i)(src))  

here is my question:

  1. can I get the fun_name list in runtime, because I want save them in a text file?

  2. I found there's common part in function defination which is "tmp = #algo", can I extract them out form those definations and can I define those functions in runtime? I want something like this:

foo.py

def foo_factory():  
    # in somehow 
    return adict      #function_name/function pair  

template = [ 
["foo_001","tmp = para + 2"], 
["foo_002","tmp = para * 2"], 
["foo_002","tmp = para + 2"], 
... 
["foo_100","tmp = #complex algo"] 

main.py

from foo import * 
dic = foo_factory(template) 
fun_name = dic.keys() 
src = 1 
rzt = []  
for i in fun_name: 
    rzt.extent(eval(i)(src))  
        #or 
    rzt.extent(dic(i)()) 

And, apologize, this question from my previous question post, but seems I didn't make my problem clear.
http://stackoverflow.com/questions/4025083/dynamic-define-the-function-name-and-function-body-with-variables-in-python

Thanks!

A: 
fnmap = {
  'foo_001': foo_001,
  'foo_002': foo_002,
  'foo_003': foo_003,
}

print fnmap['foo_002'](3)

Use a decorator to enumerate the functions if you don't feel like typing out the whole map.

Ignacio Vazquez-Abrams
@Ignacio, thanks for reply, but your answer and decorator may not what I want, i want a sinppet may generate the functions while function's name in runtime and it can conduct same action on next run.
user478514