How do you convert a string (for example, input from a textbox) into a proper function?
3 Answers
You can use eval. But be very careful! This opens up lots of security holes.
>>> s = '3+4'
>>> eval(s)
7
If you want it callable:
>>> s = '3+4'
>>> f = eval('lambda: ' + s)
>>> f()
7
More information on eval here.
Comments
def func():
print "hello"
# just eval it
eval(raw_input())
# if you just want to ask for name
fName=raw_input()
if fName in globals():
globals()[fName]()
And there could be various other ways depending on what is the objective?
2 Comments
nickf
hi anurag, just for a little beginner experiment - get the user to type a function and then i graph it
Anurag Uniyal
in that case I think eval would be just fine, you can use pycallgraph.start_trace() (pycallgraph.slowchop.com) before eval