Calling a function with a variable

114 views Asked by At

I am looping through a directory to send specific files of interest (contained in a list) to their corresponding functions, which are named similarly to the items in the list.

import os,sys,argparse
import Contact_parse
import Notes_parse
import Records_parse
...
def file_distro(dir):
'''
This function distributes the source files to their relevant parser scripts
'''
file_types = ["Contact","Notes","Records"]
for filename in os.listdir(dir):
    for t in file_types:
        if filename.startswith(t) and filename.endswith(".xml"):
            print("%s: %s") % (t,filename) # Troubleshooting, works

            try:
                func = getattr("%s_parse" % (t),main)
                    # Returns TypeError: getattr(): attribute name must be string
                #func = getattr(Contact_parse, main)
                    # Tried hardcoding to troubleshoot,
                    # also returns TypeError: getattr(): attribute name must be string
                #print("%s_parse" % t) # Troubleshooting, works
            except AttributeError:
                print("function not found: %s_parse.main" % (t))
            else:
                func()
        else:
            continue

The error received is:

getattr(): attribute name must be string

The getattr language was attempted based on searches here, and there was significant discussion between using getattr, local/globals, or a dict. I even tried hardcoding a module name, also to no avail. Any help is greatly appreciated.

2

There are 2 answers

1
Joshi Sravan Kumar On BEST ANSWER

getattr() functions takes the first argument as valid python entity (object/module...etc) and second argument as string.

In your case replacing the

getattr("%s_parse" % (t),main)

with

getattr(Contact_parse, 'main')

should work.

But if you modules name is in string form as in your case, probably you can try,

getattr(sys.modules[t + "_parse"], 'main')
0
rafalf On

this is how it works for me, however all my functions are class methods.

getattr(ClassName(), functionName)(fargs_in)