Is it possible to define a function to behave as follows?
text = "def x(a):\treturn a+1"
f = ??(text)
f(1)
>> 2
asked Feb 25, 2015 at 13:27
jamborta
5,2306 gold badges37 silver badges57 bronze badges
3 Answers 3
You can use exec()
text = "def x(a):\treturn a+1"
exec(text)
print x(5) # gives 6
answered Feb 25, 2015 at 13:30
ForceBru
45k10 gold badges72 silver badges104 bronze badges
Sign up to request clarification or add additional context in comments.
1 Comment
Kevin
Now the hard part is, getting
f(5) to give 6, when you don't know the contents of text and don't know that the function is currently called x, and so you can't just do f = xtext = "lambda a: a + 1"
f = eval(text)
f(1) # 2
answered Feb 25, 2015 at 13:31
Hugh Bothwell
57k9 gold badges91 silver badges103 bronze badges
2 Comments
Hugh Bothwell
@bhargavrao: any method of running arbitrary code is dangerous.
Hugh Bothwell
@forcebru: yes, that's why I converted it to a lambda!
here is another solution:
text = "def x(a):\treturn a+1"
f = {}
exec text in f
f['x'](1)
>> 2
answered Mar 2, 2015 at 17:28
jamborta
5,2306 gold badges37 silver badges57 bronze badges
1 Comment
CodeMouse92
Please add some explanation. Imparting the underlying logic is more important than just giving the code, because it helps the OP and other readers fix this and similar issues themselves.
lang-py
exec("print 'hello'")or any otherdefcan't be on the same line as other statements", then you can instead use lambdas:print (lambda a: a+1)(1)