← Back to Python, page 3

python-0057 · Medium mid

Explain virtual environments and dependency management for a Python project.

A virtual environment is an isolated directory with its own interpreter link and site-packages, so each project has its own dependency versions. Create one with python -m venv .venv, install with pip inside it, and record dependencies in pyproject.toml with a lock file (or a pinned requirements file) for reproducible installs.

Full answer
python
import os, subprocess, sys, tempfile
d = tempfile.mkdtemp()
env = os.path.join(d, ".venv")
subprocess.run([sys.executable, "-m", "venv", "--without-pip", env], check=True)
py = os.path.join(env, "bin", "python")
out = subprocess.run([py, "-c", "import sys; print(sys.prefix != sys.base_prefix, sys.version_info[:2])"],
                     capture_output=True, text=True).stdout.strip()
print(out)
print(sorted(os.listdir(env)))

Output:

text
True (3, 13)
['.gitignore', 'bin', 'include', 'lib', 'lib64', 'pyvenv.cfg']

The run creates a virtual environment (without pip, to keep it offline and quick) and checks from inside it that sys.prefix differs from sys.base_prefix, which is how code detects a venv. The directory contains bin, include, lib (plus a lib64 link on this system), pyvenv.cfg, and, since Python 3.13, a .gitignore that keeps the environment out of version control. Good practice: never install project packages into the system Python, commit pyproject.toml and a lock file, not the .venv folder, and separate development tools (pytest, linters) from runtime dependencies. Tools like uv or Poetry automate environments and locking; pip with requirements.txt remains common.

python
import os, subprocess, sys, tempfile
d = tempfile.mkdtemp()
env = os.path.join(d, ".venv")
subprocess.run([sys.executable, "-m", "venv", "--without-pip", env], check=True)
py = os.path.join(env, "bin", "python")
out = subprocess.run([py, "-c", "import sys; print(sys.prefix != sys.base_prefix, sys.version_info[:2])"],
                     capture_output=True, text=True).stdout.strip()
print(out)
print(sorted(os.listdir(env)))

Run on Python 3.13.5, twice in fresh interpreters, with identical output.

Key points

  • venv isolates dependencies per project
  • sys.prefix shows the active environment
  • Declare dependencies in pyproject.toml
  • Lock exact versions for reproducibility
  • Do not commit the venv

Common mistakes

  • Installing everything globally
  • Unpinned dependencies in production

Follow-ups

  • What is the difference between a library's and an application's dependency pins?
  • How does uv speed up installs?

Tips

  • Mention lock files