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!
CodePudding user response:
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.
CodePudding user response:
fn = vars()['get_' list_item]
fn()