1

I have never really fully understood how packages are handled in Python and I'm having a problem with that right now. But googling doesn't seem to help as I find the topic really confusing.

I have a project with this structure:

project_name/
    src/
        main.py
        utils/
            string_utils.py
    tests/
        test_string_utils.py

I am using Pytest for running unit testing and currently inside the "test_string_utils.py" file I have the following:

from ..src.utils.string_utils import StringUtilsClass

But I go to the folder "project_name" and try to run tests with any of this command I get errors:

$ pytest tests/

ValueError: attempted relative import beyond top-level package

I know about the -m argument for python, but it seems that running "pytest -m" has a completely different behavior.

How can I solve this? Am I using the wrong folder architecture? I don't think what I'm building should be a pip package (which would simplify imports)

Gonzalo Hernandez
  • 727
  • 2
  • 9
  • 25

1 Answers1

1

did you try : from src.utils.string_utils import StringUtilsClass without .. before src? or from string_utils import StringUtilsClass

Rambod
  • 2,355
  • 1
  • 14
  • 14
  • 1
    from src.utils.string_utils import StringUtilsClas works. How is that? is pytest loading the "src" module by itself? – Gonzalo Hernandez Nov 18 '18 at 15:20
  • "When importing the package, Python searches through the directories on sys.path looking for the package subdirectory." https://docs.python.org/3/tutorial/modules.html – Rambod Nov 18 '18 at 16:35