0

I'm having trouble with the following code:

def get_module(mod_path):
    mod_list = mod_path.split('.')
    mod = __import__(mod_list.pop(0))

    while mod_list:
        mod = getattr(mod, mod_list.pop(0))

    return mod

When I do get_module('qmbpmn.common.db_parsers') I get the error message: AttributeError: 'module' object has no attribute 'db_parsers'.

However: import qmbpmn.common.db_parsers works perfectly fine.

Alex Bliskovsky
  • 5,325
  • 7
  • 28
  • 40

2 Answers2

3

When using __import__ to import submodules, you must pass the parent package as the fromlist argument:

>>> __import__("os.path")
<module 'os' from '/usr/lib/python2.6/os.pyc'>
>>> __import__("os.path", fromlist=["os"])
<module 'posixpath' from '/usr/lib/python2.6/posixpath.pyc'>
Philipp
  • 45,923
  • 12
  • 81
  • 107
1

__import__ works with the dotted module path, so this should work

def get_module(mod_path):
    return __import__(mod_path)

or more simply

get_module = __import__

Perhaps I am misunderstanding the problem

importing a package does not automatically import all the submodules into it's namespace. For example

import qmbpmn

does not mean that

qmbpmn.common.db_parsers

will automatically resolve

John La Rooy
  • 281,034
  • 50
  • 354
  • 495