Skip to content
Latchkey

Python "python -m build" sdist Fails Preparing Metadata in CI

Building an sdist or wheel with python -m build runs the backend’s metadata hook. It fails when setup.py imports the package at build time, when file discovery needs a VCS that is absent, or when [build-system] is incomplete.

What this error means

python -m build fails during "Preparing metadata" or "Building sdist", often from a setup.py that imports the package (pulling in not-yet-installed deps) or from setuptools-scm/VCS file discovery finding no .git. The wheel/sdist is never produced.

build output
* Building sdist...
Traceback (most recent call last):
  File "setup.py", line 4, in <module>
    import mypkg   # imports the package before deps are installed
ModuleNotFoundError: No module named 'requests'
ERROR Backend subprocess exited when trying to invoke build_sdist

Common causes

setup.py imports the package at build time

Reading __version__ by importing the package forces its dependencies to be present during the build, which the isolated build env does not have.

File discovery needs an absent VCS

A backend that lists files via git (or setuptools-scm for the version) fails when .git is missing from the build context (shallow checkout, tarball, Docker context).

How to fix it

Avoid importing the package in setup.py

Read the version without importing the package - from a file or a static attribute - so the build does not need runtime deps.

setup.py
# read version without importing the package
version = {}
exec((HERE / "mypkg" / "_version.py").read_text(), version)
setup(version=version["__version__"])

Provide the VCS or a static file list

  1. Use a full checkout (fetch-depth: 0) or include .git in the Docker build context.
  2. Or add a MANIFEST.in/explicit package data so file discovery does not need git.
  3. For setuptools-scm, set SETUPTOOLS_SCM_PRETEND_VERSION when git is unavailable.

How to prevent it

  • Keep setup.py import-free; read the version statically.
  • Ensure the build context has the VCS or an explicit file manifest.
  • Declare a complete [build-system] so the backend is provisioned.

Related guides

Tired of flaky CI? Latchkey auto-heals failed jobs and retries them for you. Start free →