Reputation: 21
I know strings aren't callable however it would be nice to be able to use code like this.
def test1():
print('7')
def test2():
print('7')
def test3():
print('7')
def test4():
print('7')
def test5():
print('7')
i = input(">") #assume the input is one of the function names
i()
Upvotes: 2
Views: 64
Reputation: 16
You could make use of the ast-module:
from ast import literal_eval
literal_eval(input("What do you want to make me do? ")
literal_eval let's you call strings if they contain valid python code. However, as Lie Ryan warned above, this method gives the user the ability to call any, also possibly malicious or otherwise destructive code.
Upvotes: 0
Reputation: 953
You can use a dictionary of functions.
def test1():
print('7')
def test2():
print('7')
def test3():
print('7')
def test4():
print('7')
def test5():
print('7')
d={'test1':test1,'test2':test2,'test3':test3,'test4':test4,'test5':test5}
i = input(">") #assume the input is one of the function names
d.get(i)()
Upvotes: 1
Reputation: 64837
There are a couple ways:
The most straightforward one, collect all eligible functions in a dictionary:
functions = {f.__name__: f for f in [test1, test2, test3, test4, test5, test6]}
functions[input(">")]()
Or, a sneaky way, using globals()
, just be careful that you'll be effectively allowing the user to call any functions in the global scope, not just the ones that you think they should have:
globals()[input(">")]()
Or a super sneaky way of using eval()
or if you're doing this in a loop, just starting a shell to allow full arbitrary code execution using code.interact()
, which will also allows the user to specify the function parameters, and reformat your harddisk if the user account running the code has privilege to do so:
import code
code.interact()
Upvotes: 3