For example, if I have a function called add like
def add(x,y):
return x+y
and I want the ability to convert a string or an input to direct to that function like
w=raw_input('Please input the function you want to use')
or
w='add'
Is there any way to use w to refer to the function add?
Since you are taking user input, the safest way is to define exactly what is valid input:
If you want to evaluate strings like
'add(3,4)', you could use safe eval:evalin general could be dangerous when applied to user input.The above is safer since__builtins__is disabled andlocalsis restricted todispatcher. Someone cleverer than I might be able to still cause trouble, but I couldn’t tell you how to do it.WARNING: Even
eval(..., {'__builtins__':None}, dispatcher)is unsafe to be applied to user input. A malicious user could run arbitrary functions on your machine if given the opportunity to have his string evaluated byeval.