0

When the project directory and a subfolder has the same name, I get an import error when running pytest.

I have tried to rename the subfolder and then there is no problem.

For example with the following folder structure:

  • project/
    • project/
      • tools.py
    • foo/
      • foofile.py
    • bar/
    • unittest/
      • test_foofile.py

In project/foo/foofile.py we try to import classes from project/project/tools.py:

from project.tools import ClassA

When then running python -m pytest from the first level directory project/ i get the following error:

ImportError: cannot import name 'ClassA' from 'project.tools' (unknown location)

Is there a way to say to the interpreter that it should look into the subfolder project?

Stefan Meier
  • 123
  • 1
  • 1
  • 9
  • 1
    Have you tried `from project.project.tools import ClassA`? – Post169 Oct 16 '19 at 14:37
  • Have you verified that your current working directory is the inner `project` folder, while also ensuring the outer one is not find-able by the normal import machinery ? – Gloweye Oct 16 '19 at 14:45
  • @Post169: That is not an option since the project is used as a submodule in other projects. Then the directory name cannot be guaranteed. – Stefan Meier Oct 16 '19 at 14:49
  • It looks like you want to import from an absolute path. Here's a question about that: https://stackoverflow.com/questions/67631/how-to-import-a-module-given-the-full-path – Post169 Oct 16 '19 at 14:55
  • It's depend on sevral things : When you run pytest command, in wich folder are you ? Have you put an __init__.py file in each subfolders ? – Florian Bernard Oct 16 '19 at 15:33
  • The working directory is the outer project folder. The `__init__.py` is empty. – Stefan Meier Oct 17 '19 at 07:47

0 Answers0