tags:

views:

67

answers:

3

What's the best approach to execute the following using __import__ so that I may dynamically specify the module?

from module import *
+1  A: 

It's the same as a normal from-import call, you just pass it a list containing '*' for the fromlist:

moduleName = "foo"
__import__(moduleName, globals(), locals(), ['*'])
Michael Mrozek
That doesn't actually setup locals() though, which is the issue I'm having :)
David Cramer
According to the doc the standard `__import__` doesn't even use the `locals` argument. If you override `__builtin__.__import__` you can see exactly what happens when you run `from foo import *`, it seems to do exactly that
Michael Mrozek
It doesnt actual import the attributes, which is the problem. It loads them into memory but it doesn't set them under the current modules locals().
David Cramer
+2  A: 

__import__() never adds anything to the local scope. You will have to go through the returned module, accessing its attributes as desired.

Ignacio Vazquez-Abrams
+1  A: 

The only way I found:

module = __import__(module, globals(), locals(), ['*'])
for k in dir(module):
    locals()[k] = getattr(module, k)
David Cramer
Why would you want to do this? I smell bad code. || On the other hand, feel free to accept your own answers.
Xavier Ho
Because it's the only way to solve the problem addressed.
David Cramer