[Edu-sig] How to pass parameters to eval?
Mats Wichmann
mats@laplaza.org
Wed, 26 Sep 2001 17:22:40 -0600
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....