0

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

"*\folder\src_1\pages\page_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.

Rafael
  • 1
  • 1

3 Answers3

1

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

dwhswenson
  • 503
  • 4
  • 10
0

Can you change your imports to:

#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 *
ScoJo
  • 139
  • 5
  • When I run this inside app.py, it's alright, but when I do inside page_1.py I get ImportError: attempted relative import with no known parent package – Rafael Jan 27 '21 at 18:44
  • Yes, that's a different issue. It may be worth reading the link in @dwhswenson answer as this will better explain relative imports. – ScoJo Jan 27 '21 at 19:02
0

Please specify complete path starting from src_1. This is because the code is executed from point of view of app.py.

#On page_1.py
from src_1.pages.df_prep import df
Ajay Rawat
  • 258
  • 2
  • 6