0

I have the following project structure:

Project/
|-- src/
|   |-- package/
|       |-- __init__.py
|       |-- a.py
|       |-- b.py
|
|-- tests/
    |-- test_a.py

My __init__.py file looks like this

from .a import some_function
from .b import SOME_CONSTANT

But now I want to run the following code in test_a.py:

import package

package.some_function()

As long as it is located in the src/ directory, everything works fine, I can access all imports defined in my package. But I want it to be in the tests/ directory.

When looking at the flask repo I found that thex do it like that. For example, flasks test_appctx.py does exactly that:

import flask

flask.do_something()

How can I achieve this in my project as well?

Jannik
  • 399
  • 2
  • 5
  • 22

1 Answers1

1

You should add src/ to the folders where to look for the functions:

import sys
sys.path.append('../src')
gwido
  • 141
  • 1
  • 4
  • I guess something like that would work, but it is really good practics? If I recall correctly I read that you should avoid manipulating `sys.path`. And how does flask handle it then? I didn't see anything like that in their code (might have missed it of course) – Jannik Feb 04 '21 at 14:22
  • 1
    It's definitely not a great practice ^^' `flask` created a package which they installed with pip. In their `setup.cfg`, they point to the folder where the package is written: https://github.com/pallets/flask/blob/master/setup.cfg#L38 In a simpler way, you can gather your utilities in a folder (say `src`), create a `Project/setup.py` file and install it with `pip install -e .` from the folder `Project`. Then you can import the functions from anywhere. – gwido Feb 05 '21 at 09:22
  • Okay, thank you! I was thinking somelike that (installing the package) but couldnt find it anywhere in their code, as I'm pretty new to projects like this. That really helped. – Jannik Feb 05 '21 at 10:40