Unable to understand python 3.12 relative imports

42 views Asked by At

I have a directory structure as shown below:

postApp
    Routers
        Post.py
        User.py
        __init__.py
    Database.py
    Main.py
    Models.py
    Schemas.py
    Utils.py
    __init__.py

In the main.py file, I have tried to relative imports of database, models, schemas and utils modules. Unfortunately, it always gives error like "unable to do relative import from an unknown package name"

Normal imports do work, so I didn't pay much attention to relative imports just yet, until I defined routers folder and had to perform relative import of database and other modules in post and user. It failed with error - "cannot perform relative import beyond top level package"

these files are a present in a directory called "postApp". I put below statement in all the py files, except

    __init__ 

(they are empty).

    print(__package__ +'.'+__name__)

Then I went outside the postApp folder and run a test.py script with following statements:

    from postApp import main, database, utils, schemas
    from postApp.routers import post, user

    print(__name__)

The output in anything I would have expected to be:

    postApp.postApp.database 
    postApp.postApp.models 
    postApp.postApp.main 
    postApp.postApp.utils 
    postApp.postApp.schemas 
    postApp.routers.postApp.routers.post 
    postApp.routers.postApp.routers.user 
    __main__

I have no idea why parent package names are repeated twice. Look at the 2nd and 3rd last outputs, conceptually it should've been "postApp.routers.post" and "postApp.routers.user".

please help!

tried to do relative import but it doesn't work

0

There are 0 answers