python importlib no module named

12,258

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.

Share:
12,258

Related videos on Youtube

Sid Kwakkel
Author by

Sid Kwakkel

I've been a software developer and project manager for over 20 years. I have worked with C, C++, Java, Python, Javscript from everything on the desktop, web, and embedded devices.

Updated on October 26, 2022

Comments

  • Sid Kwakkel
    Sid Kwakkel over 1 year

    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.

    • jwodder
      jwodder over 6 years
      Is formmodules a subdirectory of cas or not?
    • Sid Kwakkel
      Sid Kwakkel over 6 years
      yes, formodules is a subdirectory of cas
  • Sid Kwakkel
    Sid Kwakkel over 6 years
    I almost missed the leading period. Works great!