2

How do I do from some.module import * where name of the module is defined in a string variable?

Andrew Bezzub
  • 15,744
  • 7
  • 51
  • 73
  • What you are doing is most probably wrong... defining variables at module level at runtime. Sooner or later you will run into trouble with this approach. Instead, store these objects into a data structure, for instance a dict and work on that. – bgusach Mar 03 '15 at 08:10
  • I am doing this to load development, production and test settings depending on environment variable – Andrew Bezzub Mar 03 '15 at 08:14
  • That's fine, though in that case you'd more likely want to emulate `import some.module` rather than `from some.module import *`. – Andrew Magee Mar 03 '15 at 08:37
  • Exactly, just conditionally import a settings module without modifying the global scope programatically. Something like ``if production: from blabla import productionsettings as settings, elif: ...`` – bgusach Mar 03 '15 at 16:14

2 Answers2

2

This code imports all symbols from os:

import importlib
# Load the module as `module'
module = importlib.import_module("os")
# Now extract the attributes into the locals() namespace, as `from .. 
# import *' would do
if hasattr(module, "__all__"):
    # A module can define __all__ to explicitly define which names
    # are imported by the `.. import *' statement
    attrs = { key: getattr(module, key) for key in module.__all__ }
else:
    # Otherwise, the statement imports all names that do not start with
    # an underscore
    attrs = { key: value for key, value in module.__dict__.items() if
              key[0] != "_" }
# Copy the attibutes into the locals() namespace
locals().update(attrs)

See e.g. this question for more information on the logic behind the from ... import * operation.

Now while this works, you should not use this code. It is already considered bad practice to import all symbols from a named module, but it certainly is even worse to do this with a user-given name. Search for PHP's register_globals if you need a hint for what could go wrong.

Community
  • 1
  • 1
Phillip
  • 13,448
  • 29
  • 41
0

In Python the built-in import function accomplishes the same goal as using the import statement, but it's an actual function, and it takes a string as an argument.

sys = __import__('sys')

The variable sys is now the sys module, just as if you had said import sys.

Reference

planet260
  • 1,384
  • 1
  • 14
  • 30