2

How can I use a list of strings ( names of submodules) to import submodules in current module ?

Current code:

from mainapp.utils import firstutil
from mainapp.utils import secondutil
from mainapp.utils import fifthutil

Required code:

needed_utils = ["firstutil","secondutil","fifthutil"]
for util_name in needed_utils:
    # use __import__ to achieve same effect as in current code
DhruvPathak
  • 42,059
  • 16
  • 116
  • 175
  • The comment tells you. Check out http://stackoverflow.com/questions/211100/pythons-import-doesnt-work-as-expected – C.B. Apr 15 '14 at 14:18

2 Answers2

2
def getobj(astr):
    """
    getobj('scipy.stats.stats') returns the associated module
    getobj('scipy.stats.stats.chisquare') returns the associated function
    """
    try:
        return globals()[astr]
    except KeyError:
        try:
            return __import__(astr, fromlist=[''])
        except ImportError:
            modname, _, basename = astr.rpartition('.')
            if modname:
                mod = getobj(modname)
                return getattr(mod, basename)
            else:
                raise

needed_utils = ["firstutil", "secondutil", "fifthutil"]
for util_name in needed_utils:
    globals()[util_name] = getobj('mainapp.utils.{m}'.format(m=util_name))
unutbu
  • 842,883
  • 184
  • 1,785
  • 1,677
1

The thing that's confusing about the __import__ function is that you need to pass the fromlist argument to do what you want:

mod1 = __import__('foo.bar')  # returns the "foo" module
mod2 = __import__('foo.bar', fromlist=['thing_in_module'])  # returns the "bar" module

As C.B. notes in a comment, a more full explanation can be found at Python's __import__ doesn't work as expected

Community
  • 1
  • 1
Eli Courtwright
  • 186,300
  • 67
  • 213
  • 256