1

How do you convert a string (for example, input from a textbox) into a proper function?

asked Oct 4, 2009 at 4:36

3 Answers 3

6

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.

answered Oct 4, 2009 at 4:37
Sign up to request clarification or add additional context in comments.

Comments

1

try this

func = ___import___('func_name')

or

if hasattr(your_module, func_name): func = getattr(your_module, func_name)

or

if func_name in globals(): func = globals[func_name]

or something etc

sra
24k8 gold badges59 silver badges89 bronze badges
answered Mar 10, 2011 at 0:15

Comments

0
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?

answered Oct 4, 2009 at 4:42

2 Comments

hi anurag, just for a little beginner experiment - get the user to type a function and then i graph it
in that case I think eval would be just fine, you can use pycallgraph.start_trace() (pycallgraph.slowchop.com) before eval

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.