[Python] Flask relative import error: "from .routes import main" not resolving even though...

Discussão em 'Python' iniciado por Stack, Maio 11, 2025.

  1. Stack

    Stack Membro Participativo

    Flask Relative Import Error — Stack Overflow Question Format


    I'm working on a Flask project where I'm using a package structure like this:

    twitter_post_enhancer/
    ├── app/
    │ ├── __init__.py
    │ ├── routes.py
    │ └── utils/
    ├── run.py


    Inside app/__init__.py, I’m trying to import my blueprint using:

    from .routes import main


    But when I run the app using:

    python run.py


    I get this error:

    ImportError: attempted relative import with no known parent package

    I've already tried:

    • Changing to from app.routes import main — works, but VS Code shows unresolved import warning.
    • Adding a .env file with PYTHONPATH=. — no change.
    • Inserting to sys.path in run.py — works but feels hacky.
    ✅ What I want:


    I want to:

    • Keep using relative imports (for modularity)
    • Run the project with python run.py from the root
    • Avoid VS Code / Pylance import errors (like "unresolved import")
    GitHub Repo (for full context):


    https://github.com/Chitranshu0/twitter-post-enhancer

    Question:


    What’s the cleanest and most Pythonic way to structure this Flask project so that:

    • Relative imports like from .routes import main work correctly
    • The app runs from run.py at root without hacks
    • VS Code and Pylance stop complaining about unresolved imports

    Any help or best practices appreciated

    Continue reading...

Compartilhe esta Página