3

I am iterating through a list and want to use the list item to call a function. This is what I have tried:

def get_list1():
    ....do something
def get_list2():
    ....do something
def get_list3():
    ....do something

data = ['list1', 'list2', 'list3']

for list_item in data:
    function_call = 'get_' + list_item
    function_call()

But I am receiving the error "TypeError: 'str' object is not callable" There are a couple of other ways that I could attack this, but this would be helpful to know for the future as well. Thanks!

larsks
  • 277,717
  • 41
  • 399
  • 399
rogueakula
  • 79
  • 5

3 Answers3

2

Hopefully that TypeError is not surprising, because when you write...

function_call = 'get_' + list_item

...you're creating a string. If you want to look up a function by that name, you can use the vars() function, like this:

def get_list1():
    print('list1')
def get_list2():
    print('list2')
def get_list3():
    print('list3')

data = ['list1', 'list2', 'list3']

for list_item in data:
    function_call = 'get_' + list_item
    fn = vars()[function_call]
    fn()

Running the above produces:

list1
list2
list3

But as @pynchia notes in a comment on another answer, this isn't a great way to structure your code: you're better off building an explicit dictionary mapping names to functions if you really need this sort of functionality. Without seeing your actual code it's hard to tell what the most appropriate solution would look like.

larsks
  • 277,717
  • 41
  • 399
  • 399
1

Just to give an example of using dictionaries (as they have been mentioned here in other answers) in case you find it useful.

def get_list1():
    print('get_list1 executes')


def get_list2():
    print('get_list2 executes')


# Create a dictionary with a reference to your functions as values
# (note no parenthesis, as that would execute the function here instead)
fns = {
    'example_key1': get_list1,
    'example_key2': get_list2,
}

print(type(fns['example_key1']))  # returns <class 'function'>

# If you still want a list
lst = list(fns)  # Create a list containing the keys of the fns dictionary
for fn in lst:
    # Iterate through the list (of keys) and execute the function
    # found in the value.
    fns[fn]()

# Or you can now just simply iterate through the dictionary instead, if you wish:
for fn in fns.values():
    fn()

This code produces:

<class 'function'>
get_list1 executes
get_list2 executes
get_list1 executes
get_list2 executes
bigkeefer
  • 576
  • 1
  • 6
  • 13
0
fn = vars()['get_' + list_item]
fn()
Daniel Barton
  • 491
  • 5
  • 14