{"id":"1eb4be36978e892c","repo":"pallets/flask","slug":"while-importing-module-name-r-an-importerror-wa","errorCode":null,"errorMessage":"While importing {module_name!r}, an ImportError was raised:\n\n{traceback.format_exc()}","messagePattern":"While importing (.+?), an ImportError was raised:\n\n(.+?)","errorType":"exception","errorClass":"NoAppException","httpStatus":null,"severity":"error","filePath":"src/flask/cli.py","lineNumber":250,"sourceCode":") -> Flask: ...\n\n\n@t.overload\ndef locate_app(\n    module_name: str, app_name: str | None, raise_if_not_found: t.Literal[False] = ...\n) -> Flask | None: ...\n\n\ndef locate_app(\n    module_name: str, app_name: str | None, raise_if_not_found: bool = True\n) -> Flask | None:\n    try:\n        __import__(module_name)\n    except ImportError:\n        # Reraise the ImportError if it occurred within the imported module.\n        # Determine this by checking whether the trace has a depth > 1.\n        if sys.exc_info()[2].tb_next:  # type: ignore[union-attr]\n            raise NoAppException(\n                f\"While importing {module_name!r}, an ImportError was\"\n                f\" raised:\\n\\n{traceback.format_exc()}\"\n            ) from None\n        elif raise_if_not_found:\n            raise NoAppException(f\"Could not import {module_name!r}.\") from None\n        else:\n            return None\n\n    module = sys.modules[module_name]\n\n    if app_name is None:\n        return find_best_app(module)\n    else:\n        return find_app_by_string(module, app_name)\n\n\ndef get_version(ctx: click.Context, param: click.Parameter, value: t.Any) -> None:\n    if not value or ctx.resilient_parsing:","sourceCodeStart":232,"sourceCodeEnd":268,"githubUrl":"https://github.com/pallets/flask/blob/6a2f545bfd8ed31e19066a299296917e034aca58/src/flask/cli.py#L232-L268","documentation":"Raised in `locate_app` when importing the target module itself succeeded in being found but an ImportError was raised from code *inside* it (detected because the traceback has depth > 1, i.e. `tb_next` is set). Flask includes the full formatted traceback so you see the real failing import rather than blaming the app module name.","triggerScenarios":"`flask run` / `flask --app mymodule` where mymodule (or anything it imports at top level) does `import somepkg` for a package that isn't installed in the active environment, or has a circular import that surfaces as ImportError.","commonSituations":"Missing dependency after switching virtualenvs or fresh clones without `pip install -r requirements.txt`; a dependency renamed or dropped in an upgrade; circular imports introduced by moving code between modules; optional imports without try/except.","solutions":["Read the embedded traceback — the last line names the actual module that failed to import — and install it (`pip install <package>`) into the same environment that runs `flask`.","Confirm you're in the right virtualenv: `which flask` and `which python` should point into the same env.","If the traceback shows a circular import, break the cycle by deferring one import into the function that uses it."],"exampleFix":"# before (mymodule.py)\nimport pandas  # not installed\n# after\npip install pandas   # in the venv that runs flask","handlingStrategy":"validation","validationCode":"python -c \"import myproject\"  # surfaces the real ImportError with full traceback before invoking flask","typeGuard":null,"tryCatchPattern":"try:\n    app = info.load_app()\nexcept NoAppException as e:\n    # message already embeds the inner traceback — log it whole\n    logging.error(\"App import failed:\\n%s\", e)\n    sys.exit(2)","preventionTips":["Read the embedded traceback — the failure is inside your module (missing dependency, syntax error), not in Flask","Keep module import side-effect-free; defer DB connections and env-dependent code into the factory or first request","Install dependencies into the same virtualenv the flask command runs from"],"tags":["flask","cli","import","dependencies"],"analyzedSha":"6a2f545bfd8ed31e19066a299296917e034aca58","analyzedAt":"2026-07-31T19:13:49.921Z","schemaVersion":2}