π Virtual Environment
A Virtual Environment (venv) is an isolated Python environment that allows you to install packages separately for each project.
It ensures that project dependencies do not conflict with each other.
π€ Why Do We Need It?
Imagine:
Project A needs
Django 3.2Project B needs
Django 4.2
Without a virtual environment:
Both versions would clash globally.
With a virtual environment:
Each project has its own isolated package version.
π§ Key Benefits
β Dependency isolation
β Avoid version conflicts
β Clean global Python installation
β Easier deployment
β Reproducible environments
ποΈ How It Works
Each virtual environment contains:
A separate Python interpreter
Its own
site-packagesfolderIndependent installed libraries
When activated:
Python uses packages inside that environment
Global packages are ignored (unless allowed)
βοΈ Setting Up a Virtual Environment
Python provides a built-in module called venv.
πͺ Step 1: Create a Virtual Environment
Inside your project folder:
π» Windows
python -m venv venvπ macOS / Linux
python3 -m venv venvHere:
-m venvβ tells Python to create a virtual environmentvenvβ name of the environment folder (you can rename it)
Example:
python3 -m venv myenvβΆοΈ Step 2: Activate the Virtual Environment
π» Windows
venv\\Scripts\\activateπ macOS / Linux
source venv/bin/activateAfter activation, your terminal will show:
(venv)That means it is active.
If your virtual environment is named myenv, then you should activate it using:
source myenv/bin/activate
OR
myenv\\Scripts\\activateβΉοΈ Step 3: Deactivate
deactivateThis returns you to the global Python environment.
π Recommended Project Structure
project/
β
βββ venv/
βββmain.py
βββ requirements.txt