Week 9: Expanding Python's Capabilities

Learn how to use modules and packages to extend Python's functionality.

Explore Chapter 9

Chapter 9: Extending Python with Modules and Packages

What are Modules? Importing and Using Modules.

A module is a file containing Python definitions and statements. Modules allow you to organize your code into reusable units. You can define functions, classes, and variables in a module and then use them in other Python programs by importing the module.

Importing Modules

The `import` statement is used to bring modules into your current program.

  • `import module_name`: Imports the entire module. You then access its contents using the module name as a prefix (e.g., `module_name.function_name`).
  • `from module_name import item_name`: Imports a specific item (function, class, or variable) from the module. You can then use the item directly without the module name prefix.
  • `from module_name import item_name as alias_name`: Imports a specific item and gives it an alias (a different name) in your program.
  • `from module_name import *`: Imports all names defined in the module (not recommended for large modules as it can pollute your namespace).

Example

# Importing the math module
import math

print(math.pi)       # Accessing the pi variable
print(math.sqrt(16))  # Calling the sqrt() function

# Importing specific items
from math import sqrt, pi

print(pi)
print(sqrt(25))

# Importing with an alias
import math as m
print(m.cos(0))

Common Built-in Modules.

Python comes with a rich set of built-in modules that provide a wide range of functionalities. Here are a few commonly used ones:

  • `math` Module: Provides mathematical functions and constants.
    import math
    
    print(math.ceil(4.2))    # 5 (rounds up)
    print(math.floor(4.8))   # 4 (rounds down)
    print(math.pow(2, 3))    # 8.0 (2 to the power of 3)
    print(math.log10(100))  # 2.0 (base-10 logarithm)
  • `random` Module: Provides functions for generating random numbers.
    import random
    
    print(random.random())       # Random float between 0 and 1
    print(random.randint(1, 10))  # Random integer between 1 and 10 (inclusive)
    numbers = [1, 2, 3, 4, 5]
    random.shuffle(numbers)      # Shuffles the list in place
    print(numbers)
    print(random.choice(numbers)) # Random element from the list
  • `datetime` Module: Provides classes for working with dates and times.
    import datetime
    
    now = datetime.datetime.now()
    print("Current date and time:", now)
    
    today = datetime.date.today()
    print("Today's date:", today)
    
    print("Year:", now.year)
    print("Month:", now.month)
    print("Day:", now.day)
  • Many others, including `os` (operating system interaction), `sys` (system-specific parameters and functions), `json` (working with JSON data), `re` (regular expressions), and more.

Packages and the `pip` Package Manager.

Packages are a way of organizing Python modules into directories and subdirectories. This helps to avoid naming conflicts and makes it easier to distribute and install collections of modules.

`pip` - The Python Package Installer

`pip` is the standard package manager for Python. It allows you to easily install, upgrade, and uninstall packages from the Python Package Index (PyPI), a vast repository of open-source Python software.

Basic `pip` Commands

You usually run `pip` commands in your terminal or command prompt.

  • Installing a package: `pip install package_name` (e.g., `pip install requests`)
  • Upgrading a package: `pip install --upgrade package_name`
  • Uninstalling a package: `pip uninstall package_name`
  • Listing installed packages: `pip list`
  • Showing information about a package: `pip show package_name`

It's generally a good practice to use virtual environments (using tools like `venv` or `conda`) to isolate your project dependencies and avoid conflicts between different projects.

Installing and Using External Libraries.

External libraries are packages that are not part of the Python standard library. They provide additional functionality for specific tasks. You install them using `pip`.

Example: Installing and Using the `requests` Library

The `requests` library simplifies making HTTP requests (for fetching data from web pages or APIs).

  1. Install `requests`:
    pip install requests
  2. Use `requests` in your code:
    import requests
    
    response = requests.get("https://www.google.com")
    
    print("Status code:", response.status_code)
    print("Content:", response.text[:200]) # Print the first 200 characters of the response

Python has a vast ecosystem of external libraries for various purposes, including:

  • Web development: Django, Flask
  • Data science: NumPy, Pandas, Scikit-learn, Matplotlib
  • Database interaction: SQLAlchemy, Psycopg2
  • Image processing: Pillow, OpenCV
  • And much more!

Learning to use external libraries effectively is a crucial skill for any Python developer.

Syllabus