You can make a dictionary mapping function names to their corresponding functions:
def foo():
print('foo called')
def bar():
print('bar called')
exposed_functions = {
'foo': foo,
'bar': bar
}
if __name__ == '__main__':
user_input = 'foo' # Pretend the user passed you this string
function = exposed_functions[user_input]
function()
This approach may seem redundant but you probably don't want the user to pass in a function like exit()
and shut down your interpreter or even something like __import__('os').system('rm -Rf --no-preserve-root /')
and do more harm.
Therefore, a whitelist is your best choice. To make it simpler, you can create a decorator to do all of this for you:
import functools
exposed_functions = {}
def expose(*names):
def decorator(function):
for name in (names or [function.__name__]):
exposed_functions[name] = function
return function
return decorator
@expose() # `name` is automatically extracted out of the function
def foo():
print('foo called')
@expose('bar', 'baz') # binds to both `bar` and `baz`
def bar():
print('bar called')
if __name__ == '__main__':
user_input = 'baz' # Pretend the user passed you this string
function = exposed_functions[user_input]
function()