1. Creating and Activating a Virtual Environment (venv)
What is a Virtual Environment?
A virtual environment is an isolated Python environment where you can install packages without affecting the global Python installation.Why Use a Virtual Environment?
- Prevents package conflicts between projects.
- Keeps project dependencies separate.
- Makes projects easier to share.
- Ensures consistent development environments.
Creating a Virtual Environment
Open a terminal in your project folder and run:python -m venv→ Runs Python’s built-in virtual environment module.venv→ Name of the virtual environment folder (can be any name).
Activating the Virtual Environment
Windows (Command Prompt)
Windows (PowerShell)
macOS/Linux
Deactivating the Virtual Environment
When finished:Checking Installed Packages
2. Managing requirements.txt
What is requirements.txt?
requirements.txt is a file that lists all Python packages required for a project.
Example:
Creating requirements.txt
After installing packages:
Installing Packages from requirements.txt
Updating requirements.txt
Whenever new packages are added:
Viewing Installed Packages
pip list→ Shows packages in a readable table.pip freeze→ Outputs packages inrequirements.txtformat.
3. Pinning Package Versions
What is Version Pinning?
Version pinning means specifying the exact version of a package to ensure everyone uses the same version. Example:Why Pin Versions?
Without pinning:- Different developers may install different versions.
- Updates can introduce bugs.
- The application may behave differently across systems.
- Consistent behavior.
- Easier debugging.
- Reliable deployments.
Installing a Specific Version
Version Specifiers
Example requirements.txt
Complete Workflow
Step 1: Create a project
Step 2: Create a virtual environment
Step 3: Activate it
Windows:Step 4: Install packages
Step 5: Save dependencies
Step 6: Share the project
Share:Typically, do not include thevenv/folder in version control. Instead, includerequirements.txtso others can recreate the environment.
Step 7: Another developer installs dependencies
Summary
python -m venv venv→ Create a virtual environment.- Activate:
venv\Scripts\activate(Windows) orsource venv/bin/activate(Linux/macOS). deactivate→ Exit the virtual environment.pip install package_name→ Install a package.pip freeze > requirements.txt→ Save installed packages.pip install -r requirements.txt→ Install dependencies from the file.- Version pinning (
==) → Ensures everyone uses the same package version for consistent and reproducible environments.