0

I have a list of functions say

list1 = ['foo','boo','koo']

now I want to call these functions one by one.

for i in range(len(list1)):
    list1[i](<argumentslist>)

This gives me an error:

TypeError: 'str' object is not callable

How Should I make this possible ?

Hima
  • 11,268
  • 3
  • 22
  • 31
  • "I have a list of functions" -- Not exactly, it looks like you have a list of strings. How you convert those strings to functions depends on a lot of things but my guess is that it'll probably involve either using `getattr` or `globals` (Or, you could actually create a list of functions rather than a list of strings that represent functions in one way or another). – mgilson Aug 07 '17 at 13:18
  • The list item are names of functions? – Klaus D. Aug 07 '17 at 13:18
  • 2
    Not again. This is technically possible, but it is **very bad design**... Call-by-name is very insecure – Willem Van Onsem Aug 07 '17 at 13:18
  • You need to use a list of actual functions -eg. `list1 = [foo,boo,koo]`, not a list of names of functions – Gerrat Aug 07 '17 at 13:20
  • 2
    Possible duplicate of [Calling a function of a module from a string with the function's name in Python](https://stackoverflow.com/questions/3061/calling-a-function-of-a-module-from-a-string-with-the-functions-name-in-python) – voodoo-burger Aug 07 '17 at 13:21
  • Possible duplicate of [Calling functions from a list issue](https://stackoverflow.com/questions/22875834/calling-functions-from-a-list-issue) – Ajax1234 Aug 07 '17 at 13:34

5 Answers5

0

Drop the ' in the list

list1 = [foo,boo,koo]
damisan
  • 1,037
  • 6
  • 17
0

Your list is does not contain a function objects, you are storing a string. Functions are first class object in python. If you want to store it as a list and call them use the function object as follows. list = [foo, bar ] list[0](args)

NishanthSpShetty
  • 661
  • 5
  • 14
0

Currently the elements in your list are strings. Given that you have defined functions foo, boo, koo you can put these in a list without the' surrounding them. I.e. you will be making a list of functions, not a list of string function names.

Bruno KM
  • 768
  • 10
  • 20
0

Not recommended but:

def hello_world(int_):
    print("hello{}".format(int_))

list_ = ["hello_world"]
arg = 2

for i in list_:
    exec("{}({})".format(i,arg))

#hello2
Anton vBR
  • 18,287
  • 5
  • 40
  • 46
0

You do not have to remove the quotes if you use **kwargs:

def the_function(**functions): 

    list1 = ['foo','boo','koo']
    for i in range(len(list1)):
        val = functions[list1[i]](3)

f1 = lambda x: pow(x, 2)
f2 = lambda x: x+3
f3 = lambda x: sum(i for i in range(x))

the_function(foo = f1, boo = f2, koo = f3)
Ajax1234
  • 69,937
  • 8
  • 61
  • 102