{"record":{"id":"8958a4f30ab773b5","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/3596b1ab61cea85edb8970e83ff61daa073facf8/src/flask/cli.py#L232-L268","documentation":"locate_app() calls __import__(module_name). If ImportError is raised and sys.exc_info()[2].tb_next exists (traceback depth > 1), the failure happened inside the imported module (a transitive import error), not because the module name itself was unknown. Flask re-raises it as NoAppException embedding the full traceback so you can see which line inside your module failed to import.","triggerScenarios":"The target module exists but executing it raises ImportError—e.g. it imports a package that is not installed, has a circular import, references a moved symbol, or has a syntax/attribute error surfacing as ImportError during its own imports. The tb_next presence distinguishes 'module blew up while loading' from 'module not found'.","commonSituations":"Missing a dependency (e.g. forgot to pip install Flask-SQLAlchemy in the active venv). A typo in an internal import statement. Activating the wrong virtualenv where the app's dependencies are absent. Running the CLI from a directory where relative imports fail.","solutions":["Read the embedded traceback in the error message to find the exact line and missing name inside your module.","Install the missing dependency or fix the offending import statement.","Ensure you run flask from the correct virtualenv / working directory where all imports resolve."],"exampleFix":"# before: mypkg/__init__.py\nfrom flask_sqlachemy import SQLAlchemy  # typo, raises ImportError\n\n# after\nfrom flask_sqlalchemy import SQLAlchemy","handlingStrategy":"try-catch","validationCode":"import importlib\n\ndef can_import_clean(module_name: str) -> bool:\n    try:\n        importlib.import_module(module_name)\n        return True\n    except ImportError:\n        return False","typeGuard":"null","tryCatchPattern":"import importlib\ntry:\n    importlib.import_module(module_name)\nexcept ImportError as e:\n    import traceback\n    tb = e.__traceback__\n    if tb and tb.tb_next:\n        print(f'Error inside module body; see traceback:\\n{traceback.format_exc()}')\n    raise","preventionTips":["Run 'python -c \"import yourmodule\"' from the same venv before invoking flask.","Pin all dependencies and verify the venv is activated in CI and locally."],"tags":["flask","cli","import","dependencies"],"backgroundTag":null,"analyzedSha":"3596b1ab61cea85edb8970e83ff61daa073facf8","analyzedAt":"2026-08-11T20:11:52.622Z","contentChangedAt":null,"schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}