When building Python applications, you will often need to use third-party packages that are not part of the standard library. To manage these libraries, we use Pip and Virtual Environments.
The Python Package Index (PyPI) is a repository of software for the Python programming language. Developers publish libraries here, and you can download them using pip (Python's package installer).
A virtual environment is a self-contained directory tree that contains a Python installation for a particular version of Python, plus a number of additional packages.
If you install all packages globally, different projects might require different versions of the same package (e.g., Project A needs Django 3.2, Project B needs Django 4.0). This leads to dependency conflicts.
Use a virtual environment for each project to isolate its dependencies.
Run this command in your project directory:
python -m venv .venvThis creates a folder named .venv containing a local copy of Python and pip.
Before installing packages, you must activate the virtual environment:
- Windows (Command Prompt):
.venv\Scripts\activate.bat
- Windows (PowerShell):
.venv\Scripts\activate.ps1
- macOS / Linux:
source .venv/bin/activate
Once activated, your terminal prompt will be prefixed with (.venv).
When you're done working, deactivate it:
deactivateWith your virtual environment activated, you can install packages:
# Install a package
pip install requests
# Install a specific version
pip install requests==2.31.0
# Upgrade a package
pip install --upgrade requests
# Uninstall a package
pip install -y requestsTo share projects, you should document the dependencies. We do this by creating a requirements.txt file.
# Generate requirements.txt
pip freeze > requirements.txt
# Install dependencies from requirements.txt
pip install -r requirements.txt- Create a virtual environment named
.venv_testin a temporary folder. - Activate it, install the
requestslibrary, and check its version usingpip show requests. - Deactivate the environment and delete the folder.