python importlib no module named

Sid Kwakkel picture Sid Kwakkel · Sep 13, 2017 · Viewed 9.9k times · Source

I am using flask and have the following structure

<root>
manage_server.py
cas <directory>
--- __init__.py
--- routes.py
--- models.py
--- templates <directory>
--- static <directory>
--- formmodules <directory>
------ __init__.py
------ BaseFormModule.py
------ Interview.py

In routes.py, I'm trying to create an instance of the Interview class in the Interview module, like so

my_module = "Interview"
module = importlib.import_module('formmodules."+my_module)

I get an error here that says

ImportError: No module named formmodules.Interview

Some info about the init files:

/cas/formmodules/__init__.py is empty
/cas/__init__.py is where I initialize my flask app. 

Let me know if it is helpful to know the contents of any of these files.

Answer

dhke picture dhke · Sep 13, 2017

This is one of the classical relative vs absolute import problems.

formmodules only exists relative to cas, but import_module does an absolute import (as with from __future__ import absolute_imports). Since formmodules cannot be found via sys.path, the import fails.

One way to fix this is to use a relative import.

If the name is specified in relative terms, then the package argument must be specified to the package which is to act as the anchor for resolving the package name.

You might want to try with:

module = importlib.import_module('.formmodules.' + my_module, package=__package__)

Note the ..

The other option is to muck about with sys.path, which really isn't necessary, here.