Call many python functions from a module by looping through a list of function names and making them variables

Tags: , , , ,



I have three similar functions in tld_list.py. I am working out of mainBase.py file.

I am trying to create a variable string which will call the appropriate function by looping through the list of all functions. My code reads from a list of function names, iterates through the list and running the function on each iteration. Each function returns 10 pieces of information from separate websites

I have tried 2 variations annotated as Option A and Option B below

# This is mainBase.py

import tld_list           # I use this in conjunction with Option A
from tld_list import *    # I use this with Option B

functionList = ["functionA", "functionB", "functionC"]
tldIterator = 0
while tldIterator < len(functionList):
    # This will determine which function is called first
    # In the first case, the function is functionA
    currentFunction = str(functionList[tldIterator])

Option A

    currentFunction = "tld_list." + currentFunction
    websiteName = currentFunction(x, y)
    print(websiteName[1]
    print(websiteName[2]
    ...
    print(websiteName[10]
    

Option B

    websiteName = currentFunction(x, y)
    print(websiteName[1]
    print(websiteName[2]
    ...
    print(websiteName[10]

Even though it is not seen, I continue to loop through the iteration by ending each loop with tldIterator += 1

Both options fail for the same reason stating TypeError: 'str' object is not callable

I am wondering what I am doing wrong, or if it is even possible to call a function in a loop with a variable

Answer

You have the function names but what you really want are the function objects bound to those names in tld_list. Since function names are attributes of the module, getattr does the job. Also, it seems like list iteration rather than keeping track of your own tldIterator index would suffice.

import tld_list

function_names = ["functionA", "functionB", "functionC"]
functions = [getattr(tld_list, name) for name in function_names]
for fctn in functions:
    website_name = fctn(x,y)


Source: stackoverflow