Hi, I appreciate all replies to my previous quesions. This time, I am trying to pass two parameter to eval function so it can evaluate and return the result base on the parameter i gave. For examples: ********func.py*************** def fun (): print v1+v2 **************pro.py*********** from func import * funname = "fun()" v1 = "Hello " v2 = "World" eval(funname) **************************** I know these code will not run. If i put fun in the same file as pro.py, it works. What i want is to let fun in func.py to have access to variable v1 and v2 which are declared in pro.py. How can i do this? Any guidance or suggestion is highly appreciated. Kim Titu __________________________________________________ Do You Yahoo!? Get email alerts & NEW webcam video instant messaging with Yahoo! Messenger. http://im.yahoo.com
At 12:30 PM 9/26/2001 -0700, you wrote:
Hi, I appreciate all replies to my previous quesions. This time, I am trying to pass two parameter to eval function so it can evaluate and return the result base on the parameter i gave. For examples:
********func.py*************** def fun (): print v1+v2
**************pro.py*********** from func import * funname = "fun()" v1 = "Hello " v2 = "World" eval(funname) **************************** I know these code will not run. If i put fun in the same file as pro.py, it works. What i want is to let fun in func.py to have access to variable v1 and v2 which are declared in pro.py. How can i do this? Any guidance or suggestion is highly appreciated.
I guess the question that comes up is why? This seems a pretty convoluted construct. From the point of view of module func, v1 and v2 are undefined; they're only visible in the namespace of the main program. You can make this work by having func.py import v1 and v2 from pro (and moving the eval to protected code: if __name__ == '__main__'). Normally you can pass eval() the namespaces it's going to operate in, but since what eval here does is run a function in a different module, you change context when the function runs. If you truly want program-global symbols, it seems better to put them in a separate file and have everybody import that. But most folks seem to think if you find a need to do that the design of the program could use some rethinking....
********func.py*************** def fun (): print v1+v2
**************pro.py***********
You can save: def fun (v1, v2): print v1 + v2 as func.py, then go:
from func import * funname = fun v1 = "Hello" v2 = "World" eval("funname(v1,v2)") HelloWorld
Of course the easier thing would be to just go:
from func import * fun("Hello","World") HelloWorld
But I assume you have your reasons... Kirby
participants (3)
-
Kirby Urner
-
Mats Wichmann
-
Titu Kim