TransWikia.com

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

Stack Overflow Asked on December 22, 2021

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

3 Answers

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)

Answered by tdelaney on December 22, 2021

You can create a dictionary to provide a name to function conversion:

def funcA(...): pass
def funcB(...): pass
def funcC(...): pass

func_find = {"Huey": funcA, "Dewey": funcB, "Louie": FuncC}

Then you can call them, e.g.

result = func_find["Huey"](...)

Answered by RufusVS on December 22, 2021

You should avoid this type of code. Try using if's, or references instead. But you can try:

websiteName = exec('{}(x, y)'.format(currentFunction))

Answered by nagyl on December 22, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP