2

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()

1
  • 1
    Why do we have a list of strings, rather than a list of functions [function1, function2, ...] so that I can just call list[counter]() directly? Commented Feb 28, 2020 at 19:59

2 Answers 2

3

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]()
Sign up to request clarification or add additional context in comments.

Comments

1

Similar to what @chepner said, I would approach the problem that way.

Potentially storing the functions in a dictionary and looking up the function based on the counter:

def function():
    print('function 1 called')

def function2():
    print('function 2 called')

counter = 0

functions = {
    1: function,
    2: function2
}

Then:

function_to_call = functions[counter + 1]

and now that when function_to_call() is called it would print function 1 called

This is how I would think about approaching the problem.

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.