Python: How to import all methods and attributes from a module dynamically

sundance picture sundance · Jan 19, 2014 · Viewed 9k times · Source

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?

Answer

BrenBarn picture BrenBarn · Jan 19, 2014

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.