eval's local arguement ignored?

Jean-Sébastien Bolduc jseb at cs.mcgill.ca
Tue Sep 23 19:23:59 CEST 2003


Hello,

I would like to associate a local namespace with a lambda function. To
be more specific, here is exactly what I would want:

def foo():
  a = 1
  f = lambda x : a*x
  return f

then if "f1 = foo()", I get a function whose parameter "a" is not in
the global scope. But my functions are not to be hard-coded. I naively
expected the following to work:

def foo(funcstring):
  a = 1
  f = eval(funcstring)
  return f

but "f2 = foo( 'lambda x : a*x' )" won't work: "f2()" will look for
"a" in the globals.

Looking at the documentation (I did!), I was then certain replacing
the evaluation with the following would work:

  f = eval(funcstring, globals(), locals())

Or, while we're at it, evaluating the whole thing outside of function
"foo":

f = eval('lambda x : a*x', globals(), {'a' : 1})

Ooops! the new function still looks for "a" in the globals... Although
I could not find any documentation about the fact, it seems the
"local" argument to "eval" has no effect in the above cases!

So for now, I'm doing something like

f = eval('lambda x : a*x', {'a' : 1})

but then my function looses access to the globals.

I know that only the very first case above gives me a function whose
"fun_closure" attribute is not "None". But still I cannot see where I
go wrong.

Thank you,

   JSeb




More information about the Python-list mailing list