How to call, in Python, a function whose name is stored in a variable?

2

There are 99 different function definitions:

def Fun_1():
...
def Fun_2():
...
def Fun_3():
...
...
...
def Fun_99():
...

The value of the variable x is randomly obtained between 1 and 99:

x = aleat(0, 99)

The variable NomeFun is obtained by concatenating "Fun_" , the value of x converted to string and "()" :

 NomeFun = "Fun_" + str(x) + "()"

How to code, in Python, the call to the function whose name matches the contents of the variable NomeFun ? It would look something like:

 execute(NomeFun)   ???
    
asked by anonymous 12.09.2017 / 00:54

3 answers

3

Because there are 99 distinct functions defined that will run randomly, I believe that the problem has been poorly developed and that this is probably not the best solution for it. However, as the problem itself was not commented on in the question, I will put a solution to what was asked.

All references to functions that exist in a given scope are available in a dictionary returned by the locals native function. So you can do:

functions = locals()
functions["Fun_1"]() # Chama a Fun_1
functions["Fun_9"]() # Chama a Fun_9
...

Then just change the value of NomeFun (and the syntax of the variable name too - see PEP8):

nome_fun = "Fun_" + str(x)

And so call the function:

functions[nome_fun]()
  

See working at Ideone .

    
12.09.2017 / 02:24
0

You can create a control function to call other functions. Example:

def execute(nomedafuncao):
    If (nomedafuncao = 'nomedafuncao'):
        funcao

Or:

 exec(nomedafuncao)
    
12.09.2017 / 01:08
0
import random
def f1(x) : return x+11
def f2(x) : return x+22
def f3(x) : return x+33

def a(x):
  return globals()["f%d"% random.randint(1,3)](x)

print(a(100),a(100),a(100))

Producing (for example)

$ python x.py
111 133 111
    
12.09.2017 / 13:33