{"id":"f39bc862f9da397e","repo":"sqlalchemy/alembic","slug":"can-t-find-python-file-s","errorCode":null,"errorMessage":"Can't find Python file %s","messagePattern":"Can't find Python file (.+?)","errorType":"exception","errorClass":"ImportError","httpStatus":null,"severity":"error","filePath":"alembic/util/pyfiles.py","lineNumber":118,"sourceCode":"def load_python_file(\n    dir_: str | os.PathLike[str], filename: str | os.PathLike[str]\n) -> ModuleType:\n    \"\"\"Load a file from the given path as a Python module.\"\"\"\n\n    dir_ = pathlib.Path(dir_)\n    filename_as_path = pathlib.Path(filename)\n    filename = filename_as_path.name\n\n    module_id = re.sub(r\"\\W\", \"_\", filename)\n    path = dir_ / filename\n    ext = path.suffix\n    if ext == \".py\":\n        if path.exists():\n            module = load_module_py(module_id, path)\n        else:\n            pyc_path = pyc_file_from_path(path)\n            if pyc_path is None:\n                raise ImportError(\"Can't find Python file %s\" % path)\n            else:\n                module = load_module_py(module_id, pyc_path)\n    elif ext in (\".pyc\", \".pyo\"):\n        module = load_module_py(module_id, path)\n    else:\n        assert False\n    return module\n\n\ndef load_module_py(module_id: str, path: str | os.PathLike[str]) -> ModuleType:\n    spec = importlib.util.spec_from_file_location(module_id, path)\n    assert spec\n    module = importlib.util.module_from_spec(spec)\n    spec.loader.exec_module(module)  # type: ignore\n    return module\n\n\ndef _preserving_path_as_str(path: str | os.PathLike[str]) -> str:","sourceCodeStart":100,"sourceCodeEnd":136,"githubUrl":"https://github.com/sqlalchemy/alembic/blob/44fb3450330204b222ff05135e1fbbbdb28c44db/alembic/util/pyfiles.py#L100-L136","documentation":"Raised as ImportError in load_python_file (pyfiles.py:118) when the requested .py file does not exist on disk AND no compiled .pyc/.pyo fallback could be located via pyc_file_from_path. Alembic tries the .py path first, then falls back to bytecode; only if both fail does it raise, meaning the module file is genuinely missing.","triggerScenarios":"Pointing alembic at a config/env.py path that does not exist; load_python_file(dir_, filename) with a typo in the filename; running in an environment where only a partial install exists (py present in source tree but file deleted); a deployment that ships only .pyc but the .pyc is also missing or in a different cache location.","commonSituations":"Misconfigured sqlalchemy.url or script_location in alembic.ini pointing at a non-existent path; renaming/moving env.py without updating references; fresh checkout missing a generated file; Docker image that excluded the migrations directory.","solutions":["Verify the file path exists: check `dir_ / filename` resolves to a real .py file.","Correct the script_location / -x argument in alembic.ini or the CLI to point at the actual env.py directory.","If running sourceless, ensure a valid .pyc is present at the expected cache location or alongside the source path.","Re-run `alembic init` if the migrations tree was deleted."],"exampleFix":"# before: alembic.ini points at a moved env\nscript_location = migrations\n# env actually at migrations/env.py but file was deleted/renamed\n\n# after: correct path\nscript_location = alembic\n# with alembic/env.py present","handlingStrategy":"validation","validationCode":"from pathlib import Path\nimport importlib.util\n\ndef python_file_loadable(dir_, filename) -> bool:\n    p = Path(dir_) / filename\n    if p.exists() and p.suffix == '.py':\n        return True\n    # check for .pyc fallback\n    spec = importlib.util.spec_from_file_location('m', p)\n    return spec is not None and Path(importlib.util.cache_from_source(p.as_posix())).exists()\n\nif not python_file_loadable(dir_, 'env.py'):\n    raise SystemExit('env.py not found and no .pyc fallback')","typeGuard":null,"tryCatchPattern":"from alembic.util.pyfiles import load_python_file\ntry:\n    module = load_python_file(dir_, 'env.py')\nexcept ImportError as e:\n    print(f'{e}. Check script_location in alembic.ini and that the file exists.')\n    raise","preventionTips":["Verify script_location and env path in alembic.ini after any move/rename.","Include the migrations directory in Docker images and CI checkouts.","Run `alembic current` as a smoke test to catch missing-file errors early."],"tags":["alembic","file-loading","import","path","configuration"],"analyzedSha":"44fb3450330204b222ff05135e1fbbbdb28c44db","analyzedAt":"2026-08-04T19:57:10.248Z","schemaVersion":2}