I'd like to load a module dynamically, given its string name (from an environment variable). I'm using Python 2.7. I know I can do something like:
import os, importlib my_module = importlib.import_module(os.environ.get('SETTINGS_MODULE'))
This is roughly equivalent to
import my_settings
(where SETTINGS_MODULE = 'my_settings'
). The problem is, I need something equivalent to
from my_settings import *
since I'd like to be able to access all methods and variables in the module. I've tried
import os, importlib my_module = importlib.import_module(os.environ.get('SETTINGS_MODULE')) from my_module import *
but I get a bunch of errors doing that. Is there a way to import all methods and attributes of a module dynamically in Python 2.7?
To load dynamically a module call import(path) as a function with an argument indicating the specifier (aka path) to a module. const module = await import(path) returns a promise that resolves to an object containing the components of the imported module. } = await import(path);
dir() is a built-in function that also returns the list of all attributes and functions in a module.
You need to use the import keyword along with the desired module name. When interpreter comes across an import statement, it imports the module to your current program. You can use the functions inside a module by using a dot(.) operator along with the module name.
If you have your module object, you can mimic the logic import *
uses as follows:
module_dict = my_module.__dict__ try: to_import = my_module.__all__ except AttributeError: to_import = [name for name in module_dict if not name.startswith('_')] globals().update({name: module_dict[name] for name in to_import})
However, this is almost certainly a really bad idea. You will unceremoniously stomp on any existing variables with the same names. This is bad enough when you do from blah import *
normally, but when you do it dynamically there is even more uncertainty about what names might collide. You are better off just importing my_module
and then accessing what you need from it using regular attribute access (e.g., my_module.someAttr
), or getattr
if you need to access its attributes dynamically.
Not answering precisely the question as worded, but if you wish to have a file as proxy to a dynamic module, you can use the ability to define __getattr__
on the module level.
import importlib import os module_name = os.environ.get('CONFIG_MODULE', 'configs.config_local') mod = importlib.import_module(module_name) def __getattr__(name): return getattr(mod, name)
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