Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

question from:https://stackoverflow.com/questions/66046972/python-how-to-import-package-from-subdirectory

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
254 views
Welcome To Ask or Share your Answers For Others

1 Answer

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

import sys
sys.path.append('../src')

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...