Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does one do the equivalent of "import * from module" with Python's __import__ function?

Tags:

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).

like image 961
Brian M. Hunt Avatar asked Sep 29 '08 04:09

Brian M. Hunt


People also ask

What does __ import __ do in Python?

The __import__() in python module helps in getting the code present in another module by either importing the function or code or file using the import in python method. The import in python returns the object or module that we specified while using the import module.

Which operator is used in Python to import modules from packages * &?

The import statement You can use the functions inside a module by using a dot(.) operator along with the module name.

What is the use of from module import * *?

from module import * can be particularly useful, if using it as: if(windows):\n\t from module_win import * \n else: \n\t from module_lin import * . Then your parent module can potentially contain OS independent function names, if the function names in module_lin & module_win have same names.


2 Answers

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)
like image 128
John Millikin Avatar answered Sep 24 '22 20:09

John Millikin


Here's my solution for dynamic naming of local settings files for Django. Note the addition below of a check to not include attributes containing '__' from the imported file. The __name__ global was being overwritten with the module name of the local settings file, which caused setup_environ(), used in manage.py, to have problems.

try:
    import socket
    HOSTNAME = socket.gethostname().replace('.','_')
    # See http://docs.python.org/library/functions.html#__import__
    m = __import__(name="settings_%s" % HOSTNAME, globals=globals(), locals=locals(), fromlist="*")
    try:
        attrlist = m.__all__
    except AttributeError:
        attrlist = dir(m)        
    for attr in [a for a in attrlist if '__' not in a]:
        globals()[attr] = getattr(m, attr)

except ImportError, e:
    sys.stderr.write('Unable to read settings_%s.py\n' % HOSTNAME)
    sys.exit(1)
like image 31
David Marble Avatar answered Sep 24 '22 20:09

David Marble