DEV Community

Shahrouz Nikseresht
Shahrouz Nikseresht

Posted on

Python Virtual Environments Explained Simply

Virtual environments let you create isolated spaces for Python projects. Each project can have its own packages and versions without conflicts.

Why use virtual environments?

Different projects might need different versions of the same package.

Without isolation, installing packages globally can cause version conflicts.

Virtual environments solve this by keeping dependencies separate.

Creating a virtual environment

Python has a built-in module called venv.

Create one:

python -m venv myenv
Enter fullscreen mode Exit fullscreen mode

This creates a folder called myenv with an isolated Python setup.

Common names: venv, .venv, or project-specific like myproject-env.

Activating the environment

Activate to use the isolated Python and packages.

On Windows:

myenv\Scripts\activate
Enter fullscreen mode Exit fullscreen mode

On macOS/Linux:

source myenv/bin/activate
Enter fullscreen mode Exit fullscreen mode

After activation, your terminal prompt usually changes (e.g., (myenv) appears).

Now python and pip refer to the isolated versions.

Installing packages

With the environment active:

pip install requests
pip install django
Enter fullscreen mode Exit fullscreen mode

These packages install only inside the current environment.

Deactivating

Leave the environment:

deactivate
Enter fullscreen mode Exit fullscreen mode

You return to the global Python setup.

Simple workflow example

# Create project folder and env
mkdir myproject
cd myproject
python -m venv venv

# Activate
source venv/bin/activate    # or venv\Scripts\activate on Windows

# Install packages
pip install flask requests

# Work on project...
python app.py

# When done
deactivate
Enter fullscreen mode Exit fullscreen mode

Checking installed packages

List packages in the current environment:

pip list
Enter fullscreen mode Exit fullscreen mode

Save requirements for sharing:

pip freeze > requirements.txt
Enter fullscreen mode Exit fullscreen mode

Install from requirements in a new environment:

pip install -r requirements.txt
Enter fullscreen mode Exit fullscreen mode

Important notes

  • Never commit the virtual environment folder to version control (it's large and system-specific).
  • Always add it to .gitignore.
  • Include requirements.txt for others to recreate the environment.
  • Use the same Python version for consistency.

Quick summary

  • Create with python -m venv name.
  • Activate with source (macOS/Linux) or Scripts\activate (Windows).
  • Install packages with pip while activated.
  • Deactivate when finished.
  • Use requirements.txt to share dependencies.

Practice setting up a virtual environment for a small project. They are essential for clean and reproducible Python development.

Top comments (0)