Question

I have bunch of modules to import and run. I have dynamically imported the modules using Dynamic module import in Python. This is in the main code. Once imported, I'm trying to run the functions in the modules.

All of the modules look like this structure

#function foo
def run(a,b)
    c=a+b
    return c

foo has been imported, I need to say something like bar=foo.run(a,b) dynamically

from this example: How to call Python functions dynamically. I have already tried the following:

i='foo'

bar = getattr(sys.modules[__name__], i+'.run()')(a,b)

traceback AttributeError: 'module' object has no attribute 'foo.run()'

I'm confused, about the attribute error. The calling functions dynamically example is clearly calling functions.

Was it helpful?

Solution

If you have imported foo already, but don't have a reference to it, use:

sys.modules['foo'].run(a,b)

OTHER TIPS

the_module.run(a, b)

Regardless of what magic made the module come into existence, it's an ordinary module object with ordinary attributes, and you know that the function is called run.

If you always know you'll use module foo, you're done. You may also need to find the module object dynamically, because the module to choose varies. If you imported the module properly, under the name you use to refer to it (e.g. foo) rather than some other name, you can also use sys.modules[mod_name]. Otherwise, you should probably have a dictionary of modules so that you can say, the_module = modules[mod_name].

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top