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).
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.
The import statement You can use the functions inside a module by using a dot(.) operator along with the module name.
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.
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)
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With