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

Asked

Viewed 8,998 times

2

You have 99 different definitions of functions:

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

the value of the variable x is obtained at random between 1 and 99:

x = aleat(0, 99)

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

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

How to encode, in Python, the call to the function whose name corresponds to the contents of the variable NomeFun? It would be something like:

 execute(NomeFun)   ???

3 answers

5

Because there are 99 distinct defined functions that will be executed 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 of functions that exist in a given scope are available in a dictionary returned by the native function locals. So you can do:

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

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

nome_fun = "Fun_" + str(x)

And so call the function:

functions[nome_fun]()

See working on Ideone.

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

0

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

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

Or:

 exec(nomedafuncao)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.