pypa/pip · error · PreviousBuildDirError

pip can't proceed with requirements '{self}' due to a pre-ex

Error message

pip can't proceed with requirements '{self}' due to a pre-existing build directory ({self.source_dir}). This is likely due to a previous installation that failed . pip is being responsible and not assuming it can delete this. Please delete it and try again.

What it means

PreviousBuildDirError raised by InstallRequirement.ensure_pristine_source_checkout when the source_dir for a requirement already contains an installable checkout/build artefact. After a failed previous install, pip refuses to silently delete the leftover build directory (it might contain user changes or partial state) and asks the user to remove it explicitly. This avoids corrupting a half-built tree.

Source

Thrown at src/pip/_internal/req/req_install.py:628

                parent_dir,
                autodelete=autodelete,
                parallel_builds=parallel_builds,
            )

    def needs_unpacked_archive(self, archive_source: Path) -> None:
        assert self._archive_source is None
        self._archive_source = archive_source

    def ensure_pristine_source_checkout(self) -> None:
        """Ensure the source directory has not yet been built in."""
        assert self.source_dir is not None
        if self._archive_source is not None:
            unpack_file(str(self._archive_source), self.source_dir)
        elif is_installable_dir(self.source_dir):
            # If a checkout exists, it's unwise to keep going.
            # version inconsistencies are logged later, but do not fail
            # the installation.
            raise PreviousBuildDirError(
                f"pip can't proceed with requirements '{self}' due to a "
                f"pre-existing build directory ({self.source_dir}). This is likely "
                "due to a previous installation that failed . pip is "
                "being responsible and not assuming it can delete this. "
                "Please delete it and try again."
            )

    # For editable installations
    def update_editable(self) -> None:
        if not self.link:
            logger.debug(
                "Cannot update repository at %s; repository location is unknown",
                self.source_dir,
            )
            return
        assert self.editable
        assert self.source_dir
        if self.link.scheme == "file":

View on GitHub (pinned to d7d0d0a394)

Solutions

  1. Delete the offending directory named in the message (self.source_dir): 'rm -rf <path>'.
  2. Clear pip's global build/cache dirs: 'pip cache purge' and remove /tmp pip-* build dirs.
  3. If it is a VCS editable, also remove the project's .egg-info and any src/*.egg-link.
  4. Re-run pip; if it fails again, capture the underlying build error before retrying.

Example fix

# before
pip install ./myproject   # failed once, retry fails with PreviousBuildDirError

# after
rm -rf /tmp/pip-*/myproject   # or the path from the message
pip install ./myproject
Defensive patterns

Strategy: validation

Validate before calling

import os, glob
def stale_build_dirs() -> list[str]:
    return [d for d in glob.glob('/tmp/pip-*') + glob.glob(os.path.expanduser('~/.cache/pip')) if os.path.isdir(d)]

Type guard

def has_stale_build_dir(source_dir: str) -> bool:
    import os
    from pip._internal.utils.misc import is_installable_dir
    return os.path.isdir(source_dir) and is_installable_dir(source_dir)

Try / catch

from pip._internal.exceptions import PreviousBuildDirError
try:
    run_pip(['install', './myproject'])
except PreviousBuildDirError as e:
    print(f'removing stale build dir: {e}'); import shutil, re; shutil.rmtree(re.search(r'\(([^)]+)\)', str(e)).group(1), ignore_errors=True)

Prevention

When it happens

Trigger: A prior 'pip install' of the same sdist/VCS requirement failed midway, leaving <build_dir>/<req>/ populated and installable; rerunning pip hits ensure_pristine_source_checkout and is_installable_dir returns True. Common with retries after a build error or an interrupted Ctrl-C.

Common situations: Ctrl-C during 'pip install'; backend crashed during build; switching branches in a '-e git+...' editable that left a stale checkout; CI retry on the same workspace without cleanup; pip's --no-clean keeping the build dir.

Related errors


AI-assisted analysis of pypa/pip@d7d0d0a394 (2026-08-04). Data as JSON: /data/errors/8d2fbdb865b9e364.json. Report an issue: GitHub.