Python – How does one do the equivalent of “import * from module” with Python’s __import__ function

pythonpython-import

Given a string with a module name, how do you import everything in the module as if you had called:

from module import *

i.e. given string S="module", how does one get the equivalent of the following:

__import__(S, fromlist="*")

This doesn't seem to perform as expected (as it doesn't import anything).

Best Solution

Please reconsider. The only thing worse than import * is magic import *.

If you really want to:

m = __import__ (S)
try:
    attrlist = m.__all__
except AttributeError:
    attrlist = dir (m)
for attr in attrlist:
    globals()[attr] = getattr (m, attr)