Codeskill

Learn to code, step by step

Virtual Environments: Keeping Your Projects Organized and Secure

Isolated spaces for each project’s dependencies so packages do not clash between projects.

What is a virtual environment?

A virtual environment is a self-contained directory with its own Python binary and its own installed packages. What you install inside it stays inside it.

Why use one?

Without virtual environments, you tend to hit two problems:

  • Conflicting dependencies: project A needs Django 3, project B needs Django 4.
  • Global package clutter: everything installed system-wide, hard to track what belongs where.

One environment per project keeps things clean and reproducible.

Creating a virtual environment

The venv module is built in. From your project directory:

python3 -m venv myenv

This creates a myenv folder with a complete Python environment inside.

Activating a virtual environment

You must activate before using it. The command depends on your OS:

  • Windows:
  .\myenv\Scripts\activate
  • macOS and Linux:
  source myenv/bin/activate

Your prompt usually shows the environment name once active.

Managing packages

With the environment active, use pip as normal. Packages install only into this environment:

pip install requests

Deactivating

Type deactivate to return to your global Python:

deactivate

Requirements files

Record what is installed so others (or future you) can recreate the environment:

pip freeze > requirements.txt

That writes every package and version to requirements.txt.

Installing from a requirements file

In a fresh virtual environment:

pip install -r requirements.txt

Best practices

  • One environment per project: keeps dependencies separate.
  • Commit requirements.txt: track dependency changes in Git.
  • Keep secrets out of code: use environment variables for API keys and similar.
PreviousModules and Packages: Expanding Your Python Toolbox