Search code examples
pythonpython-module

What is the most pythonic way to import 'sibling' modules into one another?


By 'sibling' modules, I mean two submodules that exist at the same depth within a parent module.

I'm trying to create a flask project using Flask-Restful, and it recommends structuring the project using this schema:

myapi/
    __init__.py
    app.py          # this file contains your app and routes
    resources/
        __init__.py
        foo.py      # contains logic for /Foo
        bar.py      # contains logic for /Bar
    common/
        __init__.py
        util.py     # just some common infrastructure

I really like this structure, but I'm not sure how to import something from the 'common' module into the 'resources' module. Can anyone help me out?


Solution

  • In common/__init__.py

    from myapi.common.utils import A, B
    

    In resource/foo.py

    from myapi.common import A
    

    You can also relative imports in __init__.py like from .utils import A.