Virtual Environments, pip & Poetry
Manage dependencies like a professional
Stop installing packages globally. Learn how to isolate projects with venv, pin exact versions with pip freeze, declare dependencies in pyproject.toml, and choose between Poetry, uv, and the standard toolchain.
$ python -m venv .venv $ source .venv/bin/activate # macOS / Linux $ pip install requests $ pip freeze > requirements.txt
2.32.3
๐ฆ Why Virtual Environments Exist
One Python installation cannot satisfy every project's dependency needs
The Dependency Conflict Problem
Imagine two projects on your machine. Project A needs version 1.0 of a library, and Project B needs version 2.0. If you install both into the same global Python environment, one of them will break. The versions conflict, and there's no way around it โ unless each project gets its own isolated environment.
A virtual environment is a self-contained directory tree that holds its own
copy of the Python interpreter and its own site-packages folder. When you activate it,
your terminal session is reconfigured so that python and pip point to the
environment's copies rather than the global installation [citation:6].
The benefits are isolation (Project A and B never see each other's packages), reproducibility (capture exact versions in a requirements file), and cleanliness (your system Python stays untouched). On Linux especially, installing packages into the system Python can interfere with the operating system's own package manager [citation:7].
The standard toolchain ships with Python
venv has been part of Python since 3.3, and it installs pip into every environment it creates by default [citation:2][citation:7]. No external tools required to get started.
- โCreate and activate virtual environments with
venv - โInstall, upgrade, and remove packages with
pip - โFreeze dependencies to
requirements.txtfor reproducibility - โDeclare modern project metadata in
pyproject.toml - โUnderstand when to use Poetry or uv instead of the standard tools
๐ Creating a Virtual Environment
One command, one directory, total isolation
Convention: name the environment .venv and place it in your project root. The leading dot keeps it hidden in your shell, and most tools (VS Code, Git ignore templates) recognize it by default [citation:6].
# Navigate to your project folder first cd ~/projects/my-app # Create the environment python -m venv .venv # This creates: # .venv/bin/python (the interpreter) # .venv/lib/site-packages (where pip installs) # .venv/pyvenv.cfg (configuration)
| Option | Effect | When to use |
|---|---|---|
--system-site-packages | Exposes global packages | Rarely โ only for special tooling |
--clear | Wipes existing directory first | Recreating a broken environment |
--upgrade | Upgrades an existing environment | After upgrading Python in-place |
--without-pip | Skips pip installation | Custom bootstrapping only |
--upgrade-deps | Updates pip & setuptools to latest | Fresh environment, latest tooling |
.venv directory to version control. Add it to .gitignore. Environments are machine-specific and can be recreated from a requirements file.What's inside a virtual environment
.venv/ โโโ bin/ # Unix: python, pip, activate scripts โ โโโ python โ โโโ pip โ โโโ activate โ โโโ activate.csh โ โโโ activate.fish โโโ lib/ โ โโโ site-packages/ # installed packages live here โโโ include/ โโโ pyvenv.cfg # environment config # On Windows, the layout differs: .venv/ โโโ Scripts/ # python.exe, pip.exe, activate.bat โโโ Lib/ โ โโโ site-packages/ โโโ pyvenv.cfg
๐ Activating and Deactivating
Point your shell at the environment's interpreter
Activation is not strictly required. You can always run commands using the environment's full interpreter path (e.g., .venv/bin/python script.py). But activation is convenient and gives you a visual prompt [citation:11].
| Platform / Shell | Activate command | Deactivate |
|---|---|---|
| macOS / Linux (bash/zsh) | source .venv/bin/activate | deactivate |
| macOS / Linux (fish) | source .venv/bin/activate.fish | deactivate |
| Windows (CMD) | .venv\Scripts\activate.bat | deactivate |
| Windows (PowerShell) | .venv\Scripts\Activate.ps1 | deactivate |
| Git Bash (Windows) | source .venv/Scripts/activate | deactivate |
PowerShell execution policy
If PowerShell refuses to run Activate.ps1, you may need to allow local scripts once with: Set-ExecutionPolicy -Scope CurrentUser RemoteSigned. This only affects your user account and does not require administrator privileges [citation:11][citation:14].
# After activation, the prompt shows the environment name (.venv) $ which python /path/to/project/.venv/bin/python (.venv) $ python -c "import sys; print(sys.prefix)" /path/to/project/.venv # Deactivate returns to the global interpreter (.venv) $ deactivate $ which python /usr/bin/python3
sys.prefix != sys.base_prefix, you're inside one [citation:11].๐ฅ Installing Packages with pip
The standard installer, included with every virtual environment
Always use python -m pip rather than bare pip. This guarantees you're using the pip that belongs to the active Python interpreter, avoiding PATH confusion when multiple Pythons are installed [citation:2][citation:7].
# Install the latest version python -m pip install requests # Install a specific version python -m pip install requests==2.31.0 # Install a minimum version (quote for shell safety) python -m pip install "requests>=2.31" # Upgrade an existing package python -m pip install --upgrade requests # Uninstall python -m pip uninstall requests # List installed packages python -m pip list # Show details about a package python -m pip show requests
Version specifiers
| Specifier | Meaning | Example |
|---|---|---|
== | Exactly this version | django==4.2.7 |
>= | At least this version | requests>=2.31 |
~= | Compatible release (same minor) | django~=4.2.0 โ 4.2.x |
< / > | Strict comparison | flask<3.0 |
!= | Exclude a version | numpy!=1.24.0 |
| No specifier | Latest available | pandas |
pip install grabs the latest release. That's fine for exploration, but production projects should pin versions to avoid surprise breakage.Installing from a requirements file
# requirements.txt requests==2.31.0 flask>=3.0,<4.0 pytest~=8.0 # Install everything listed python -m pip install -r requirements.txt
๐ Requirements Files & pip freeze
Reproducible installs across machines
pip freeze outputs every installed package and its exact version. Redirect it to a file and you have a snapshot of the environment that can be recreated anywhere.
# After installing your dependencies python -m pip freeze > requirements.txt # Example output: # certifi==2024.2.2 # charset-normalizer==3.3.2 # idna==3.6 # requests==2.31.0 # urllib3==2.2.1 # Recreate the exact environment elsewhere python -m pip install -r requirements.txt
requirements.in for direct dependencies (human-edited) and requirements.txt for the frozen output (tool-generated).
Pinning strategies
| Strategy | File looks like | Best for |
|---|---|---|
| Loose | requests | Libraries, exploration |
| Minimum bound | requests>=2.31 | Applications with CI |
| Compatible range | requests~=2.31.0 | Balancing stability and patches |
| Exact pin | requests==2.31.0 | Production, reproducibility |
โ๏ธ pyproject.toml โ The Modern Standard
One file for metadata, dependencies, and build configuration
pyproject.toml is the standard configuration file for Python projects. It declares your project's metadata, dependencies, and build system in a single TOML file, replacing the older setup.py and setup.cfg combination [citation:3][citation:8].
[build-system] requires = ["setuptools>=61.0"] build-backend = "setuptools.build_meta" [project] name = "my-app" version = "0.1.0" description = "A sample Python project" readme = "README.md" requires-python = ">=3.10" dependencies = [ "requests>=2.31", "flask>=3.0,<4.0", ] [project.optional-dependencies] dev = [ "pytest>=8.0", "black", "mypy", ] [project.scripts] my-app = "my_app.cli:main"
| Section | Purpose | Example |
|---|---|---|
[build-system] | How to build the package | setuptools, hatchling |
[project] | Core metadata and dependencies | name, version, dependencies |
[project.optional-dependencies] | Extras like dev tools | dev = ["pytest"] |
[project.scripts] | CLI entry points | my-app = "module:func" |
pip install -e ".[dev]" installs your project in editable mode along with the dev extra dependencies. This is the standard way to set up a development environment from a pyproject.toml [citation:3].
pyproject.toml declares abstract dependencies (ranges). It does not pin exact versions. For reproducible installs, you still need a lockfile or a frozen requirements file.๐ Poetry vs uv โ Modern Alternatives
Tools that manage environments and lockfiles for you
Poetry
EstablishedPoetry manages dependencies, virtual environments, and packaging in one tool. It creates a poetry.lock file for reproducible installs and uses pyproject.toml for configuration.
# Install Poetry (recommended: pipx) pipx install poetry # Create a new project poetry new my-app cd my-app # Add a dependency poetry add requests # Install all dependencies from lockfile poetry install # Run a command inside the environment poetry run python script.py
uv
FastestRecommendeduv is an extremely fast package and project manager written in Rust. It replaces pip, pip-tools, pipx, poetry, pyenv, and virtualenv with a single tool that's 10โ100x faster [citation:4].
# Install uv (standalone installer) curl -LsSf https://astral.sh/uv/install.sh | sh # Create a new project uv init my-app cd my-app # Add a dependency (updates pyproject.toml + uv.lock) uv add requests # Sync the environment uv sync # Run a command uv run python script.py
When to use which
| Tool | Best for | Trade-off |
|---|---|---|
venv + pip | Learning, simple scripts, CI pipelines | Manual lockfile management |
poetry | Libraries, teams wanting packaging + env in one | Slower than uv; opinionated |
uv | Speed-critical workflows, modern projects | Newer; less entrenched |
uv pip interface. If you want a 10โ100x speedup without changing your existing pip workflow, you can migrate incrementally [citation:4].๐๏ธ Mini Project โ A Reproducible Setup
Put everything together in one workflow
This walkthrough creates a project from scratch with a virtual environment, installed dependencies, a frozen requirements file, and a pyproject.toml for metadata.
# 1. Create the project directory mkdir my-app && cd my-app # 2. Create and activate a virtual environment python -m venv .venv source .venv/bin/activate # macOS/Linux # .venv\Scripts\activate # Windows # 3. Upgrade pip itself python -m pip install --upgrade pip # 4. Install dependencies python -m pip install requests flask pytest # 5. Freeze exact versions python -m pip freeze > requirements.txt # 6. Create a minimal pyproject.toml cat > pyproject.toml << 'EOF' [project] name = "my-app" version = "0.1.0" requires-python = ">=3.10" dependencies = [ "requests>=2.31", "flask>=3.0", ] EOF # 7. Verify python -m pip list cat requirements.txt
Package Version ------------------ --------- blinker 1.7.0 certifi 2024.2.2 charset-normalizer 3.3.2 click 8.1.7 flask 3.0.2 idna 3.6 itsdangerous 2.1.2 jinja2 3.1.3 markupsafe 2.1.5 pip 24.0 pytest 8.0.2 requests 2.31.0 urllib3 2.2.1 werkzeug 3.0.1
Notice that pip freeze captures transitive dependencies โ certifi, charset-normalizer, idna, and urllib3 were all installed automatically as dependencies of requests. That's exactly what you want for reproducibility.
requirements.txt and pyproject.toml, never .venv/. A fresh clone plus python -m venv .venv && pip install -r requirements.txt recreates the exact environment.
โ Frequently Asked Questions
Common questions about virtual environments and dependency management
For any real project, yes. Installing packages globally risks version conflicts between projects and can break system tooling on Linux. The only exception is a disposable environment (a Docker container, a CI runner) where isolation is already provided by the surrounding system.
venv is the standard library tool, included with Python 3.3+ [citation:2]. virtualenv is a third-party predecessor that works on older Python versions and offers extra features like faster creation. For modern Python, venv is sufficient and requires no installation.
No. Virtual environments contain hard-coded paths. If you move the project, recreate the environment at the new location and delete the old one [citation:1]. Moving it will cause software installed inside to misbehave.
When multiple Python versions are installed, a bare pip command might resolve to a different interpreter than the python command. python -m pip guarantees you're using the pip that belongs to the active Python, which is especially important inside virtual environments [citation:2][citation:7].
requirements.txt is a flat list of packages for installation, typically with exact pins. pyproject.toml is a project metadata file that declares abstract dependencies, build configuration, and entry points [citation:3]. Modern projects often use both: pyproject.toml for declaration, requirements.txt (or a lockfile) for reproducible installs.
Poetry solves more problems: it manages environments, creates lockfiles, handles packaging, and publishes to PyPI. pip is a lower-level installer. For simple scripts, pip + venv is fine. For libraries and multi-developer projects, Poetry (or uv) reduces friction substantially.
Yes. Lockfiles (poetry.lock, uv.lock, frozen requirements.txt) should be committed so that every developer and CI run gets the exact same versions. They guarantee reproducibility across machines and time.
Try uv pip install instead of pip install. uv is a drop-in replacement that's 10โ100x faster [citation:4]. It uses the same package index and respects the same requirements files, so migration is minimal.
๐ Where to Go Next
Keep building on what you just learned