How do I do from some.module import *
where name of the module is defined in a string variable?
Asked
Active
Viewed 239 times
2

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 Answers
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.
-
this is not user given name, I need to load dev, test or prod settings file depending on a value in environment variable – Andrew Bezzub Mar 03 '15 at 08:17
-