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.
* 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_sdistCommon 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.
# 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
- Use a full checkout (
fetch-depth: 0) or include.gitin the Docker build context. - Or add a
MANIFEST.in/explicit package data so file discovery does not need git. - For setuptools-scm, set
SETUPTOOLS_SCM_PRETEND_VERSIONwhen git is unavailable.
How to prevent it
- Keep
setup.pyimport-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.