How do you use a string from a list to call a function with the same name, in Python?

Truewarlock :

I wasn't able to find a satisfying answer anywhere so I decided to ask.

Let's say we have a global counter and a global list

counter=0
list=["function1","function2",..."functionN"]

we also we have those functions defined:

def function1():
  pass
def function2():
  pass
.
.
.
def functionN():
  pass


I have an interface with a button, every time I press it, the global counter increments. Depending on the number, I need to call a different function. I can implement this with if and elif but I don't think it's that smart. Is there a way I can call those functions using the list?

Example

when counter=0=>list[0]=>the string is 'function1'=> call function1()

press button again

counter=1=>list[1]=>the string is 'function2' => call function2()

Quinn :

You can call a function by its name like this:

locals()["myfunction"]()

or:

globals()["myfunction"]()

or if its from another module like this:

import foo
getattr(foo, 'myfunction')()

Or if it suits your use case, just use a list of functions instead of a list of strings:

def func1():
    print("1")

def func2():
    print("2")

def func3():
    print("3")

def func4():
    print("4")

some_list=[func1, func2, func3, func4]

# call like this
for f in some_list:
    f()

# or like this
some_list[0]()

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=16513&siteId=1