deepak
deepak

Reputation: 349

can i execute a lambda function passed as a string

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

Answers (1)

timgeb
timgeb

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

Related Questions