Search code examples
pythonimporterrorrelative-import

ImportError in Python 3.8.6


I am using python 3.8.6 to build a simple web app with the module Flask and the folder structure looks exactly like this:

web-app
 ├── main.py
 └── site
     ├── __init__.py
     ├── auth.py
     └── models.py

In __init__.py there is a function called create_app() and this function must be accessed by my main.py.

# site/__init__.py
from flask import Flask

def create_app():
    app = Flask(__name__)
    app.config.SECRET_KEY = ""
    return app
enter code here

In my main.py I am importing the create_app() like this:

# main.py
from .site import create_app

app = create_app()

if __name__ == "__main__":
    app.run(debug=True)

But when I try to run my main.py, raises the following error:

Traceback (most recent call last):
  File "c:/Users/User/Desktop/website/main.py", line 1, in <module>
    from .site import create_app
ImportError: attempted relative import with no known parent package

I've already try to import without the dot before the folder's name, like from site import create_app, but that also didn't work, the error message just changes to ImportError: cannot import name 'create_app' from 'site' (C:\Python38\lib\site.py).


Solution

  • Change it to:

    from web-app.site import create_app

    An from a directory one level up run:

    python -m web-app.main

    There are apparently built-in module named site in Python, so there's a bit of name collision here.