inspectorG4dget
inspectorG4dget

Reputation: 113915

Importing a function (by name) from a filename

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

Upvotes: 0

Views: 73

Answers (1)

BrenBarn
BrenBarn

Reputation: 251363

If you have imported the module as object mod, and var is a string containing the name of the function you want, you can do getattr(mod, var) to get the function (or class, value, etc.) of that name from the module.

Upvotes: 2

Related Questions