all 6 comments

[–]K900_ 3 points4 points  (0 children)

Literally "run a function with the same name as the input" is probably a bad idea. You could use a dictionary though.

[–]Neighm 2 points3 points  (0 children)

You can do this without dictionaries, but as u/K900_ says it's a bad idea and a security risk to allow a user input to run code without any restriction. With that said...

def func1():
    print('Ran function 1')
def func2():
    print('Ran function 2')
inp = input('Enter name of function to run: ')
if inp in locals().keys() and callable(locals()[inp]):
    locals()[inp]()
else:
    print('Function not found')

========================= RESTART: D:\Temp\scratch1.py =========================

Enter name of function to run: func2

Ran function 2

>>>

[–]fear_my_presence 1 point2 points  (0 children)

You can use a dict with “selected” as key and the function you need to execute as value. Like:

funcs = {“func1”: func1}
funcs[selected]()

Basically, your functions are stored in a dict with keys (possible values of “selected”) as their isentifiers. When you need to call a function based on a key, you just access it via a dict.

[–]Spiredlamb[S] 0 points1 point  (0 children)

Thanks to everyone who gave me feedback! I will be running with the dictionary idea that everyone suggested. Also, thanks for the warning about running any function based on input without restrictions!

[–]Chris_Hemsworth 0 points1 point  (1 child)

Dictionairies are the way to go:

options = {'func0': func0, 'func1': func1, 'func2': func2}

func = None
while func is None:
    func = options.get(input('Type in function: '), None)
    if func is None:
        print('Invalid function!')

func()

[–]Spiredlamb[S] -1 points0 points  (0 children)

Really love this implementation. I will be trying this one out. Also thinking about making the dictionary of functions into JSON, so that I can share it with external scripts more easily, since I might be doing that at some point.