Search code examples
python-3.xfunctionvariables

Python3: Is it possible to use a variable as part of a function call


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!


Solution

  • 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