1

I have the following project structure in Pycharm -

project/
    src/
        main.py
        config/
            __init__.py
            settings.py
        package1/
            __init__.py
            client.py # Imports settings from config using -> from ..config import settings
        tests/
            __init__.py
            test.py

So here my client.py imports settings -

from ..config import settings

main.py imports client -

from package1.client import clientFunction # ClientFunction is the method defined inside client.py

I use pytest to run the tests. So now when i run the pytest configuration, in my test cases i import main. I dont see any errors in my code but when the tests run it says -

from ..config import settings
E   ValueError: attempted relative import beyond top-level package

How can i fix this? Seems like pytest is taking a different path to execute the tests and hence the relative imports are going beyond the top level.

Dan
  • 79
  • 10
  • Welcome to Stack Overflow. I'm not 100% sure about the relative import syntax but there seems to be a space in the last import `.. config`. There's also no `__init__.py` in the `src` making it a namespace package, I'm not sure if relative imports work in such a case. If you are installing the package just `from config import settings` should work (which might not if you don't install the package but works after installing it). – bad_coder May 20 '21 at 15:37
  • Sorry, that was a typo. Changed it. The src folder is the source folder which has packages within it. Is it ideal to have the __init__.py in it? What do you mean by installing it ? I have a venv where the system imports happened based on poetry but these are packages written by me. – Dan May 20 '21 at 16:00
  • maybe setting the pytest working directory can fix it? – Dan May 20 '21 at 16:02
  • mmm, the pytest working directory is mostly about where you can just type `pytest something` and the pytest configuration file takes all its paths relative to that, see [the configuration files](https://docs.pytest.org/en/reorganize-docs/customize.html). About using a `src` layout I recommend [this post](https://stackoverflow.com/q/50155464) together with [Installing from a local src tree](https://packaging.python.org/tutorials/installing-packages/#installing-from-a-local-src-tree). I really don't know about poetry specifics... – bad_coder May 20 '21 at 17:09
  • marking the src directory as source root did the trick. Thanks for your help – Dan May 21 '21 at 17:01
  • Good to know it worked out for you. – bad_coder May 21 '21 at 17:02

0 Answers0