The run time error by import python module

779 Views Asked by At

I am trying to make correctly import the function "mmenu" from another module

I got a run time error:

Traceback (most recent call last):
  File "path.../venv/src/routes.py", line 4, in <module>
    from venv.src.main_menu import mmenu
ModuleNotFoundError: No module named 'venv.src'

after Java this Python is a bit of a mystery to me :)

I have 2 files in the same "src" directory

main_menu.py

    def mmenu():
        menu = [{"name": "HOME", "url": "home"},
            {"name": "fooo", "url": "foo"},
            {"name": "bar", "url": "bar"},
            {"name": "CONTACT", "url": "contact"}]
        return menu

routes.py

    from flask import Flask, render_template, request, flash, session, redirect, abort
    from jinja2 import Template
    from flask.helpers import url_for
    from venv.src.main_menu import mmenu

    app = Flask(__name__)
    
    menu = mmenu
    
    @app.route("/")
    @app.route("/index")
    def index():
        # return "index"
        print("loaded" + url_for('index'))
        return render_template('index.html', title="Index page", menu=menu)

    # ...

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

import was generated by IDE like:

from venv.src.parts.main_menu import mmenu
1

There are 1 best solutions below

1
On

Your IDE (which IDE?) is likely misconfigured if it generates imports like that.

The venv itself, nor any src directory within them, shouldn't be within import paths.

You never mention you have a parts/ package, but from the import I'll assume you do, and your structure is something like

venv/
  src/             # source root
    routes.py
    parts/         # parts package
      __init__.py  # (empty) init for parts package
      main_menu.py

With this structure, main_menu is importable as parts.main_menu from routes.py assuming you start the program with python routes.py.

If you have __init__.py files in venv/ and/or src/, get rid of them; you don't want those directories to be assumed to be Python packages.