Search code examples
pythonpackagedirectory-structurerelative-import

Making every module in a package accessible from within?


How is a Python package supposed to be structured to make everything possible for any module inside of it?

My file structure is as follows:

Project/
    |---log/
    |   |---some logs
    |
    |---src/
        |---foo/
        |   |---__init__.py
        |   |---analyse.py
        |   |---export.py
        |    
        |---bar/
        |   |---__init__.py
        |   |---log.py
        |   |---dbhandler.py
        |   
        |---__init__.py
        |---main.py

main.py initialises everything. I want to import foo/analyse.py to bar/dbhandler.py, but I only receive an error:

AttributeError: 'module' object has no attribute 'analyse'

I've tried several statements:

import Project.src.foo.analyse
import src.foo.analyse
import foo.analyse
import analyse

All of them give the same error. I've also tried:

from .. import foo.analyse
from .. import analyse

But I received:

ValueError: Attempted relative import beyond toplevel package

I've gone through about fifty threads on StackOverflow and countless articles on the internet. From everything I've found the import src.foo.* statement should work from anywhere inside the package, if only the __init__.py file is located in each folder.

Did anyone have the same problem?


Solution

  • Ensure that your PYTHONPATH contains Project/src and then use

    import foo.analyse