Working with Libraries and Virtual Environments

This lesson focuses on managing external libraries and creating isolated environments for Python projects to maintain dependencies effectively.

Topics Covered:

  1. What Are Libraries in Python?
    • Explanation of Python libraries and their role in extending functionality.
    • Examples: NumPy, Pandas, Requests, Flask, etc.
  2. Installing Libraries Using pip
    • Introduction to pip, Python’s package manager.
    • Basic commands:
Bash
pip install library_name  
pip uninstall library_name  
pip list  

Introduction to Virtual Environments

  • What is a virtual environment, and why is it important?
  • Avoiding dependency conflicts with isolated environments.

Creating and Activating Virtual Environments

  • Windows
Bash
python -m venv env  
env\Scripts\activate  

Mac/Linux

Bash
python3 -m venv env  
source env/bin/activate  

Managing Dependencies

  • Freezing dependencies with pip freeze
Bash
pip freeze > requirements.txt  

Installing dependencies from requirements.txt

Bash
pip install -r requirements.txt  
  1. Popular Python Libraries
    • For Data Science: NumPy, Pandas, Matplotlib, scikit-learn.
    • For Web Development: Flask, Django.
    • For Web Scraping: BeautifulSoup, Scrapy.
    • For APIs: Requests, FastAPI.
  2. Best Practices for Library Management
    • Keep dependencies to a minimum.
    • Always use a virtual environment for each project.
    • Regularly update dependencies to patch security vulnerabilities.

Code Examples

1. Installing and Using a Library

Bash
pip install requests  

Python
import requests  

response = requests.get("https://api.github.com")  
if response.status_code == 200:  
    print("API Response:", response.json())  

2. Creating and Activating a Virtual Environment

Windows:

Bash
python -m venv myenv  
myenv\Scripts\activate  

Mac/Linux:

Bash
python3 -m venv myenv  
source myenv/bin/activate  

3. Managing Dependencies

Freezing Current Dependencies:

Bash
pip freeze > requirements.txt  

Installing Dependencies from File:

Bash
pip install -r requirements.txt  

Example: Managing a Data Science Project

Bash
# Step 1: Create a virtual environment  
python3 -m venv dataenv  

# Step 2: Activate the virtual environment  
source dataenv/bin/activate  

# Step 3: Install required libraries  
pip install numpy pandas matplotlib  

# Step 4: Freeze dependencies  
pip freeze > requirements.txt  

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top