Python Import – Equivalent of ‘import * from module’ Using __import__

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 Answer

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)
Related Question