Skip to main content
Stack Overflow
  1. About
  2. For Teams

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

Required fields*

Python import module not found errors

I have a directory setup as follows:

/directory
/directory/__init__.py
/directory/setup.py
/directory/app/db.py
/directory/app/__init__.py

The /directory/__init__.py file contains the line "import app" which then fails in /directory/app/__init__.py due to the line "import db" when I try to run the setup.py file.

HOWEVER, if I change the error line to "from app import db" then it works fine. Why is this? I'm guessing it has to do with the fact I run it from a parent directory. Is there any way to make this work? Or do I just change all of the imports to "from app import x" even when it's being called from the app folder?

Thanks for any clarification.

Edit: Here's the error:

Traceback (most recent call last):
File "setup.py", line 2, in <module>
import app
File "/directory/app/__init__.py", line 1, in <module>
import db
ImportError: No module named 'db'

Edit2: Here's the /directory/app/__init__.py file (/directory/__init__.py is empty)

import db
from flask import Flask, render_template
DEBUG = True
app = Flask(__name__)
app.config.from_object(__name__)
@app.route("/")
def hello():
 return render_template()
def run(host, port):
 db.init_db()
 app.run(host=host, port=port)

Final Edit: I had rephrased my question here and was given the right answer. I wasn't sure if the python3 change was relevant. Thanks!

Answer*

Draft saved
Draft discarded
Cancel
1
  • 1
    Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center. Commented Aug 23, 2023 at 16:08

lang-py

AltStyle によって変換されたページ (->オリジナル) /