Creating and Activating Virtual Environments with venv
You'll learn: How to create isolated Python environments using the built-in venv module and activate them for your data science projects.
The Core Idea
The venv module ships with Python 3.3+ and lets you create lightweight, self-contained Python environments. Think of it as setting up a clean laboratory for each experiment—no cross-contamination between projects. When you learned about virtual environments conceptually, you understood why they matter; now you'll learn how to actually create and use them.
Creating a Virtual Environment
Navigate to your project directory and run:
python -m venv myenv
This command tells Python to run the venv module and create a new environment folder called myenv (you can name it anything, but venv, env, or .venv are common conventions). Inside this folder, Python creates a copy of the Python interpreter and a space for isolated packages.
Activating the Environment
Before installing packages or running code, you must activate the environment:
On macOS/Linux:
source myenv/bin/activate
On Windows:
myenv\Scripts\activate
Once activated, your command prompt changes (usually showing the environment name in parentheses), and any pip install command now installs packages only in this isolated environment, not globally.
Deactivating
When finished working in that environment:
deactivate
This returns you to your system's default Python environment.
Key Takeaway: Use python -m venv <name> to create isolated environments, activate them with platform-specific commands before work, and deactivate when done—ensuring each project has its own clean, reproducible dependency set.