I’m writing a code tracer that uses the trace module. In order to use the trace module, I need to first be able to call the function in question.
I have been successful in importing the module which contains the function definition, by using imp as follows:
mod = imp.load_source(os.path.basename(fpath).rpartition('.py')[0], fpath)
where fpath is the path to the module that needs to be imported.
I do not know ahead of time, what function/class I need to import from mod. This is identified in a str variable (let’s call it var for the sake of this example).
For example, fpath could be '/Users/username/.../myPythonModule.py' and var could be 'foo'
How would I go about importing foo from mod?
I’m on python2.7, if it matters
If you have imported the module as object
mod, andvaris a string containing the name of the function you want, you can dogetattr(mod, var)to get the function (or class, value, etc.) of that name from the module.