0

I have a code in which the user chooses the function he wants to execute. There is no definite amount of functions as the functions may increase in the future. I am storing the value fetched from the User input into a variable. I want to make the variable callable.

functions = ['add','sub','mul']
a = 10
b = 5

x = input('Choose a function : ')

def add():
    print(a+b)
def mul():
    print(a*b)
def sub():
    print(a-b)

x()

I want the variable 'x' to be called and executed as a function.

1
  • You can assign functions to variables. x=add Then you can call x as a function. x(1,2) Commented Jun 3, 2019 at 19:55

3 Answers 3

1

I think, correct solution for this will be dict. Also it gives you some flexibility to give different string keywords for functions. Code:

def add(a, b):
    print(a + b)


def mul(a, b):
    print(a * b)


def sub(a, b):
    print(a - b)


functions = {
    'add': add,
    'sub': sub,
    'mul': mul
}

a = 10
b = 5

x = input('Choose a function : ')

if x not in functions:
    print(f"Function \"{x}\" is not defined.")
else:
    functions[x](a, b)

But if you think that it's 100% neccesary to call function by string name, you can get reference to function from globals():

func = globals().get(x, None)
if not x:
    print(f"Function \"{x}\" is not defined.")
else:
    func(a, b)
Sign up to request clarification or add additional context in comments.

Comments

0

eval() could work for you, just know that it allows arbitrary code execution, so be careful how you allow values to get passed to it.

E.g.:

$ python
Python 3.7.2 (default, Feb 12 2019, 08:15:36) 
[Clang 10.0.0 (clang-1000.11.45.5)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> def a():
...     print('a')
... 
>>> def b():
...     print('b')
... 
>>> func = eval('a')
>>> func()
a
>>> func = eval('b')
>>> func()
b
>>> 

Or with the user selection step:

# ...
>>> func_choice = input('Choose a function: ')
Choose a function: a
>>> func = eval(func_choice)
>>> func()
a
>>> 

7 Comments

TypeError: 'str' object is not callable
While this technically works, it's a bad idea in general to use eval.
Is it right to use eval() when there is user input involved?
It's potentially risky, especially in the way I've shown here. But if you trust the user and validate the input, it can be okay to use, especially where you need a lot of flexibility (e.g., while under development).
@ayushsingh, you can easily replace eval(func_name) with globals()[func_name]() which will be more "secure".
|
0

I notice you don't use functions, but you're on to something there. It should be a dictionary of names to functions

def add():
    ...

functions = {'add': add,'sub': sub, 'mul': mul}

choice = input('Choose a function : ')
f = functions[choice]

f()

Comments

Your Answer

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.