Sub topic 11
Keeping environments out of version control and rebuilding them
This chapter assumes you can create and activate a virtual environment with python -m venv, install packages with python -m pip, and write a requirements.txt with pip freeze. You also need basic Git usage: git status, git add, and git commit. The chapter covers where an environment should live in a project, why it should never be committed, and how to throw one away and rebuild it with confidence.
Why an environment is not source code
A virtual environment is a build artifact. It is generated from two inputs: a Python interpreter and a list of packages. If you keep those two inputs, you can regenerate the environment at any time. Committing the environment itself causes several problems:
- It is large. A modest environment holds thousands of files, often tens or hundreds of megabytes. Every clone downloads all of them.
- It is tied to one machine. Scripts in
bin/(orScripts\on Windows) contain absolute paths to the interpreter, andpyvenv.cfgrecords the location of the base installation. On another computer those paths do not exist. - It is tied to one operating system. Compiled extension modules built for Linux do not load on Windows or macOS, and the folder layout differs between platforms.
- It pollutes history. Each package upgrade rewrites many files, and diffs of binary files tell reviewers nothing.
What you commit instead is the recipe: your source code, requirements.txt (and a constraints file if you use one), and any project metadata such as pyproject.toml.
A typical project layout
Place the environment inside the project directory, in a folder named .venv. Many editors and tools look for this name and select the interpreter automatically.
my-project/
├── .git/
├── .gitignore
├── .venv/ <- generated, never committed
├── requirements.txt <- committed
├── constraints.txt <- committed (optional)
├── pyproject.toml <- committed (if the project is installable)
├── src/
│ └── mypackage/
└── tests/Using one environment per project, always in the same place, means you never wonder which environment belongs to which project.
Ignoring the environment with .gitignore
Create a .gitignore file in the project root and list the directory:
.venv/
__pycache__/The trailing slash tells Git that the pattern matches directories only. __pycache__/ holds compiled bytecode that Python writes next to your source files. Like the environment, it can be regenerated, so it does not belong in version control either.
The pattern __pycache__/ has no leading path, so it matches at any depth in the tree. The pattern .venv/ matches a directory with that name at any depth as well. If you want it to match only at the project root, write /.venv/.
You can ask Git which rule is ignoring a path:
git check-ignore -v .venvThe output names the file, line number, and pattern that matched. If the command prints nothing, the path is not ignored.
Other names are common, so a shared .gitignore often lists several. A pattern such as venv/ or env/ only helps if your team actually uses those names. Pick one name for the team and write it down in the README.
Removing an environment that was already committed
Adding a line to .gitignore does not affect files Git already tracks. If someone committed .venv/, remove it from the index while leaving the files on disk:
git rm -r --cached .venv
git add .gitignore
git commit -m "Stop tracking the virtual environment"The --cached option removes the files from Git's index only. Without it, Git also deletes the directory from your disk. Old commits still contain the files, so the repository stays large. Shrinking history needs a separate tool and coordination with everyone who has a clone, which is outside this chapter.
What to commit so the environment can be rebuilt
The environment is only disposable if the recipe is complete. Check that your repository answers three questions:
- Which packages? A
requirements.txtthat lists the direct dependencies, or the exact set frompip freeze. - Which versions? Version specifiers in that file, or a constraints file that fixes them.
- Which Python? The interpreter version is not recorded in
requirements.txt. State it in the README, or inrequires-pythoninpyproject.tomlif you have one.
The third item is the one most often forgotten. A requirements file produced with Python 3.12 may fail to install on Python 3.9 because a pinned release no longer supports it. Writing the supported Python range down prevents confusing errors later.
Rebuilding an environment
Because the environment is derived, the fix for most environment trouble is to delete it and create it again. On Linux or macOS:
deactivate 2>/dev/null
rm -rf .venv
python3 -m venv .venv
source .venv/bin/activate
python -m pip install -r requirements.txtOn Windows PowerShell:
deactivate
Remove-Item -Recurse -Force .venv
py -m venv .venv
.venv\Scripts\Activate.ps1
python -m pip install -r requirements.txtDeactivate first so your shell is not left pointing at a directory that no longer exists. The deactivate function is only defined while an environment is active, so in a plain shell the command reports an error. That is harmless; the Linux example above silences it.
The venv module can also clear an existing directory for you:
python3 -m venv --clear .venvWith --clear, venv deletes the contents of the target directory before creating the environment. Use it only on a directory that holds nothing but an environment.
If you rebuild often, add --upgrade-deps, which upgrades pip in the new environment to the latest version from the package index:
python3 -m venv --upgrade-deps .venvThe following diagram shows the full cycle. The committed files are the only inputs, and the environment is an output.
Verifying the rebuild
A rebuild is only trustworthy if you check the result. After installing, run three checks:
python -c "import sys; print(sys.prefix)"
python -m pip check
python -m pip listsys.prefixshould point inside your project's.venv. If it shows a system path, the environment is not active.pip checkreports installed packages whose dependencies are missing or incompatible. It printsNo broken requirements found.when everything is consistent.pip listshows what actually got installed, which you can compare against what you expected.
Then run your test suite. The tests are the real proof that the rebuilt environment behaves like the old one.
Edge cases and gotchas
Do not move or rename an environment. Scripts such as pip in .venv/bin start with a line pointing at the interpreter's absolute path. Moving the directory leaves those paths stale, and commands fail with errors like bad interpreter: No such file or directory. Do not copy an environment between machines or folders either. Create a new one at the new location and reinstall.
Upgrading Python breaks old environments. pyvenv.cfg points to the base installation that created the environment. If you remove or upgrade that Python (for example through a system update or Homebrew), the environment's interpreter can stop working. Rebuild the environment with the new Python.
Editable installs need reinstalling too. If you installed your own project with python -m pip install -e ., include that step in the rebuild. A requirements file does not capture it unless you add -e . as a line in the file.
Frozen files can contain stray entries. pip freeze lists everything in the environment, including packages you installed once for experiments. When you regenerate requirements.txt, review the diff before committing it.
CI should rebuild, not restore. Continuous integration systems should create a fresh environment from the committed files on every run. A cache of downloaded packages speeds this up, but caching the environment itself reintroduces the problems described above.
Keep secrets out of reach. Environments sometimes hold files you did not write, such as cached credentials in a pip configuration or a .env file you placed nearby. Ignoring the environment does not ignore those. Add .env and similar files to .gitignore explicitly.
A short onboarding checklist
Put these steps in your README so a new contributor can build the environment without asking anyone:
- Install the required Python version.
- Run
python3 -m venv .venv. - Activate with
source .venv/bin/activate(Linux or macOS) or.venv\Scripts\Activate.ps1(Windows PowerShell). - Run
python -m pip install -r requirements.txt. - Run
python -m pip checkand then the tests.
If these five steps work on a clean machine, the environment is truly disposable.
Exercises
Exercise
You added .venv/ to .gitignore, but git status still lists files under .venv as modified. What is happening, and what command fixes it without deleting the environment from your disk?
Show answer
Git is already tracking those files because an earlier commit included them, and .gitignore does not affect tracked files. Run git rm -r --cached .venv, then commit the change. The --cached option removes the files from the index only, so the directory stays on disk.
Exercise
A teammate copies the whole .venv folder from their laptop to a different directory on the same laptop, and pip now fails with bad interpreter. Why, and what should they do?
Show answer
Scripts in the environment's bin directory contain the absolute path of the original interpreter location, and pyvenv.cfg records the original setup. Moving or copying the folder leaves those paths stale. They should delete the copy, create a new environment in the new location with python -m venv, and reinstall with python -m pip install -r requirements.txt.
Exercise
Your requirements.txt installs cleanly on your machine but fails on a colleague's machine with a message that a pinned release requires a newer Python. Which of the three rebuild questions did the repository fail to answer, and where could you record the answer?
Show answer
It failed to state which Python version to use. Record the supported range in the README, or in requires-python in pyproject.toml if the project has one, so everyone builds the environment with a compatible interpreter.