Pythonadvanced 8 min
Isolate each project's dependencies with venv and pip, and record them in requirements.txt.
What a virtual environment is, how to create and activate one, install packages with pip, and share dependencies with requirements.txt.
Project A needs version 1 of a library and project B needs version 2. If everything installs into one place they clash. A virtual environment gives each project its own private set of packages, so nothing breaks when you start another project.
A virtual environment (venv) is a folder that contains its own copy of the Python interpreter and its own installed packages. You switch it on (activate) for a work session.
Commands are typed in a terminal on your own computer.
Add .venv/ to .gitignore: the environment is rebuilt from requirements.txt, not committed.
A requirements.txt looks like this. This script reads it and prints what would be installed:
requirements.txt names a package, optionally with a version rule.== pins an exact version, >= sets a minimum, and a bare name means any version.requests: ==2.31.0, flask: >=3.0 and numpy: any version, then 3 packages.pip install -r requirements.txt does the real work of installing these on your machine.Add a line pandas<=2.2 and confirm it is read. Then add a comment line starting with #.
.venv to git.requirements.txt after installing something.pip from a different Python than the one in your environment. Use python -m pip.python -m venv, activate, then pip install.requirements.txt and keep .venv out of git.You finished the Python track. Try the practice exercises to lock it in.
# 1. create (once per project)
python -m venv .venv
# 2. activate
# Windows PowerShell: .venv\Scripts\Activate.ps1
# macOS / Linux: source .venv/bin/activate
# 3. install packages
pip install requests
# 4. record them
pip freeze > requirements.txt
# 5. someone else recreates the same setup
pip install -r requirements.txt
# 6. leave the environment
deactivaterequirements = """
requests==2.31.0
flask>=3.0
numpy
"""
packages = {}
for line in requirements.strip().splitlines():
line = line.strip()
if not line or line.startswith("#"):
continue
for op in ("==", ">=", "<="):
if op in line:
name, version = line.split(op)
packages[name] = op + version
break
else:
packages[line] = "any version"
for name, rule in packages.items():
print(f"{name}: {rule}")
print(len(packages), "packages")