Virtual Environments & Dependencies
Master Python package management. Learn venv, pip, requirements.txt, and modern packaging.
Master Python package management. Learn venv, pip, requirements.txt, and modern packaging. This hands-on tutorial focuses on practical implementation of virtual environments & dependencies concepts.
Virtual Environments & Dependencies
Virtual environments isolate project dependencies, preventing conflicts between different projects.
Why Virtual Environments?
Problem: Different projects need different package versions.
Solution: Create isolated environments for each project.
Creating Virtual Environments
To create a virtual environment, use the venv module included with Python.
Terminal Commands
# Create environment named "myenv"
python -m venv myenv
# Activate (Windows)
myenv\Scripts\activate
# Activate (Mac/Linux)
source myenv/bin/activate
Once activated, your terminal prompt will change (e.g., (myenv) C:\...).
Package Management with pip
pip is the package installer for Python. You use it to install libraries from the Python Package Index (PyPI).
Common Commands
# Install a package
pip install requests
# Install specific version
pip install flask==2.0.1
# Upgrade a package
pip install --upgrade pandas
# Uninstall
pip uninstall numpy
requirements.txt
A requirements.txt file lists all dependencies for a project. This ensures other developers install the exact same versions.
Example File
flask==2.3.0
requests>=2.0.0
gunicorn
Workflow
# Save current environment to file
pip freeze > requirements.txt
# Install everything from file
pip install -r requirements.txt
Modern Packaging: pyproject.toml
Best Practices
AI Mentor
Confused about "Python virtual environments venv pip package management"? Ask our AI mentor for a simplified explanation.
Quiz
Quiz
Question 1 of 3What is a virtual environment?
Key Takeaways
✅ Virtual environments isolate project dependencies.
✅ python -m venv creates environments.
✅ pip manages packages.
✅ requirements.txt lists dependencies.
✅ pyproject.toml is the modern standard.
Keep coding! 🚀