7

How come when I type the following

eval("mult = lambda x,y: (x*y)")

I get this as an error? What's going on?

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<string>", line 1
    mult = lambda x,y: (x*y)
         ^
SyntaxError: invalid syntax

What am I doing wrong? If I enter the expression as is (no eval) I get no error, and can use mult to my hearts content.

tekknolagi
  • 10,663
  • 24
  • 75
  • 119
  • 2
    Seems to be a lot of questions trying to dynamically create variables today. I can't remember _ever_ needing to do this in real code. – John La Rooy Jun 16 '11 at 06:25
  • i'm screwing around with a badly written Python postfix language – tekknolagi Jun 16 '11 at 07:10
  • 1
    You may be interested in http://stackoverflow.com/questions/8696602/python-3-2-1-execx-y-sets-a-value-in-a-toy-example-but-not-in-the-full –  Jan 16 '12 at 05:09

3 Answers3

12

You want to use exec instead of eval. I don't know why you would want to do this though when you can just use mult = lambda x,y : (x*y)

>>> exec("mult = lambda x,y : (x*y)")
>>> mult
<function <lambda> at 0x1004ac1b8>
>>> mult(3,6)
18
GWW
  • 43,129
  • 11
  • 115
  • 108
  • what if i have a function and want to return the value of calling `mult(x, y)`? – tekknolagi Jun 16 '11 at 05:59
  • @tekknolagi: I am not sure what you mean? calling `mult(x,y)` returns the value. – GWW Jun 16 '11 at 06:00
  • This will not work reliably. In particular, this *will not* work in Python 3.x inside a function. –  Jan 16 '12 at 05:08
9

Eval does expressions, it doesn't assign.

>>> eval("lambda x,y: y*x")
<function <lambda> at 0xb73c779c>
>>> eval("lambda x,y: y*x")(2, 4)
8

You must assign the eval'd expression to a variable:

>>> mult = eval("lambda x,y: y*x")
>>> mult(2, 3)
6
mike3996
  • 17,047
  • 9
  • 64
  • 80
2
mult = eval("lambda x,y: (x*y)")
clyfish
  • 10,240
  • 2
  • 31
  • 23