Skip to content Skip to sidebar Skip to footer

Python Import Error - Run Unittest

Why am I getting import error for a module I have in the project. All the packages are under the project, they all have __init __.py and other scripts do not give the same error. P

Solution 1:

Looks like you are missing a project's root path in PYTHONPATH

From the docs (Modules - The Module Source Path)

When a module named spam is imported, the interpreter first searches for a built-in module with that name. If not found, it then searches for a file named spam.py in a list of directories given by the variable sys.path. sys.path is initialized from these locations:

  • The directory containing the input script (or the current directory when no file is specified).
  • PYTHONPATH (a list of directory names, with the same syntax as the shell variable PATH).
  • The installation-dependent default.

If this solution doesn't work for you, please post the project's tree to make it easier find the problem.

Solution 2:

I've experienced a similar problem with import error when running unit tests (with correct importable structure), but the cause and the solution are different to described in the answer above. Still this is relevant and may help somebody.

In my case I have structure like that (__init__.py present but omitted below for brevity):

mypkg
  \-- foo.py
another
tests
  \-- some
        \-- <tests here>
      mypkg  <--- same name as top level module mypkg
        \-- test_a.py

When running from top level directory imports in test_a.py of modules from mypkg were failing:

# test_a.pyfrom mypkg import foo  # causes ModuleNotFoundError: No module named 'mypkg.foo'

Renaming mypkg folder under tests folder into something else solved the problem.

Post a Comment for "Python Import Error - Run Unittest"