R
R
Reikoni2021-07-31 16:02:32
Python
Reikoni, 2021-07-31 16:02:32

How to execute a function that I will define myself?

There are three functions:

def say(what):
    print(what)

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

def connect(to):
    print(f"You are connected to {to}!")

And there is also input.
The essence of the program is that the user enters the name of the function with its arguments, if they are needed. And the program must perform the desired function with arguments, if they are needed.
Example of work:
INPUT: What are we doing? say hello world
OUTPUT: hello world

INPUT: What do we do? connect mywifi
OUTPUT: You are connected to mywifi

INPUT: What are we doing? sum 3 5
OUTPUT: 8
How to implement this? There is an idea to use if conditions and just cut off the name of the Function and say the arguments, but is it possible to write this in a more rational way?

Answer the question

In order to leave comments, you need to log in

4 answer(s)
M
Michael, 2021-07-31
@ifullut

kirillinyakin suggested a more compact method, in turn I can offer you a modified version of your idea, where there will be no recursive error, and the sum will be for an independent number of numbers.

def say(what):
    print(what)

def get_sum(*args):
    items = [int(item) for item in list(*args)]
    print(sum(items))

def connect(to):
    print(f'You are connected to "{to}"!')

dict_func = locals()
print(dict_func['connect'])

while True:
    request = input('Enter your request: ')
    if 'say' in request and 'say' in request.split()[0]:
        say(request.replace('say ', ''))
    elif 'sum' in request:
        get_sum(request.split()[1:])
    elif 'connect' in request and 'connect' in request.split()[0]:
        connect(request.replace('connect ', ''))
    elif request == 'exit':
        print('Goodbye!'); break
    else:
        print("I don't understand you, try again!")

K
kirillinyakin, 2021-07-31
@kirillinyakin

Python has a locals() function that returns all variables in the current namespace, it remains only to iterate through this dictionary, where the key is the name of the variable, and the value is a reference to it, and check for a match between the names and that the value contains a function

D
dmshar, 2021-07-31
@dmshar

The options proposed above are not bad, but they are strictly tied to specific functions and even their number. Add one more function - and you need to make changes to the script. What is not good.
There is another option. We write one auxiliary microfunction that will read the user's response and, depending on the first word, call a function whose name matches this word. To do this is relatively simple. But not everyone is familiar with such a cunning way.
Just:

def ExecIt(func, param):
    return func(param)

Then in the script itself, it is enough to insert only two lines:
request = input('Enter your request: ')
ExecIt(globals()[request.split()[0]], request.split(maxsplit=1)[1])

and get a UNIVERSAL solution.
The only thing to consider is that the functions themselves can have a different number of parameters. For example, in the TS in the sum function there are two of them, and in the rest there is one. And maybe more. Or less. Therefore, the most correct way is to parse the parameters, if necessary, or already in the functions themselves. Hopefully it won't be difficult for TS. In any case, this is a topic for another question.

K
Kirill Gusarev, 2021-07-31
@kaka888

There are exec and eval functions, they run the passed text as code.
Example:
exec("sum(4, 5)")
result = eval("sum(4, 5)")

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question