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

Categories

0 votes
664 views
in Technique[技术] by (71.8m points)

module - Python Mutilevel Import

I'm having trouble if relative imports. The directory structure is:

folder
    app.py
    src_1
         __init__.py
        database
            db_declare.py
            __init__.py
        pages
            page_1.py
            df_prep.py
            __init__.py

Okay, now I have on:

#On app.py
from src_1.pages import page_1

#On page_1.py
from df_prep import df

#On df_prep.py
from database.db_declare import *

But I still get

"*foldersrc_1pagespage_1.py", line 9, in <module>
    from df_prep import df

ModuleNotFoundError: No module named 'df_prep'

When I run app.py. I've tried adding ".." to sys.path, but it ends up adding to many "..". I tried to Thank you. I wanted to keep the imports inside the scripts unchanged, meaning if two scripts are in the same folder there should be no reason to write from pages.df_prep import df inside pages_1.py. I'm open to suggestions, but I really would not like to change too much about the file structure.

question from:https://stackoverflow.com/questions/65925182/python-mutilevel-import

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

1 Answer

0 votes
by (71.8m points)

src_1 is a package. folder is not, so app.py is not in a package (but everything else is).

Relative imports in packages require .:

# in page1.py
from .df_prep import df
# in df_prep.py
from ..database.db_declare import *

See detailed answers here: Relative imports for the billionth time


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...