3

Consider a string which represents a lambda function

fn = "lambda x: x+10"

I need to do something like this,

map (fn,xrange(10))

how can i get code/function from string in python ?

deepak
  • 349
  • 1
  • 5
  • 21
  • 1
    You may [eval](http://stackoverflow.com/questions/1832940/is-using-eval-in-python-a-bad-practice) it, but why do you have a string in the first place? – kennytm May 19 '16 at 10:25
  • 2
    This is a job for `eval`, but `eval` (and `exec`) should generally be avoided because they can be a security risk. For details, please see [Eval really is dangerous](http://nedbatchelder.com/blog/201206/eval_really_is_dangerous.html) by SO veteran Ned Batchelder. – PM 2Ring May 19 '16 at 10:39

1 Answers1

6

You could eval that string, but I don't recommend it.

>>> f = eval("lambda x: x+10")
>>> f(3)
13

eval is unsafe so I strongly suggest that you fix your problem upstream, why do you have a string in the first place? But technically, yeah, eval is the answer.

timgeb
  • 76,762
  • 20
  • 123
  • 145