Reputation: 349
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 ?
Upvotes: 3
Views: 1120
Reputation: 78750
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.
Upvotes: 6