Skip to content
Advertisement

Python Importing package at same level but different directory

python version:3.9.6

I cannot seem to get this to work I know there are a million posts that are the same as this but the solutions never seem to work for me. I’ve run into this before and always end up just restructuring the folders to include all files in one path which is obviously not ideal. So here I am once again asking you guys for help.

My folder structure is as follows

|project
    |my_service
        -my_service.py
    |tests
        - tests.py

I’m trying to get the function get_num_back from my_service.py and import it into tests.py.

I’ve tried relative imports from ..my_service.my_service import get_num_back this doesn’t work because from what I’ve read I cannot hit the root folder.

I’ve then tried absolute import from my_service.my_service import get_num_back which is the answer I see works for everyone else but it doesn’t seem to work for me. I’ve then tried from project import my_service as well as from project.my_service import my_service. as far as I understand with my python version I do not need __init__.py but I’ve also tried it with that as well. the error

ModuleNotFoundError: No module named 'project'

Please settle this for me once and for all!

Advertisement

Answer

Always run py.test from your project directory.

Because from that directory it can actually find my_service.


For more information, read up on relative imports in the language reference documentation.

Advertisement