Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
672 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 Reply

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...