An Introduction to the Art of Computer Programming Using Python in the Age of Generative AI

XII. Modules and Packages

Introduction to Modules

In Python, a module is simply a file containing Python code—such as functions, classes, and variables—that you can reuse in other programs. By separating related functionalities into distinct modules, you can organize your code more effectively, reduce duplication, and make maintenance easier. Modules also facilitate collaboration by allowing different team members to work on separate files without interfering with each other’s code.


# Creating a module named 'my_module.py'
def greet(name):
    print(f"Hello, {name}!")
        

# Using the module in another Python script
import my_module
my_module.greet('Alice')
        

The import statement lets you bring in the module’s functionality under a specified namespace. You can also use from my_module import greet to import specific functions or attributes into your current namespace.

Using Built-in Modules

Python includes a rich standard library of built-in modules. These modules cover common tasks—like math operations, file I/O, date/time handling, and system-level operations—so you can address many needs without installing extra packages. By leveraging these built-in modules, you can write efficient, reliable code that utilizes Python’s well-tested core functionality.


import math
result = math.sqrt(25)
print(result)
        

Python’s standard library includes modules like os for interacting with the operating system, sys for system parameters, and json for working with JSON data—among many others. Check Python’s official docs or use the help() function to learn more about each module’s capabilities.

Creating and Using Packages

A package is a collection of related modules organized into a directory structure. Packages let you group modules by functionality, making complex projects easier to manage. They also enable clear hierarchical namespaces via dot notation. Each package should contain an __init__.py file (even if empty) to tell Python that this directory is a package.


# Creating a package named 'my_package'
# Directory structure:
# my_package/
#     __init__.py
#     my_module.py

# Inside 'my_module.py':
def greet(name):
    print(f"Hello, {name}!")

# Using the package in another Python script
from my_package import my_module
my_module.greet('Bob')  # Output: Hello, Bob!
        

This allows for a scalable design. You can add more modules inside my_package, each responsible for a different aspect of your program, while maintaining a well-organized codebase. To import them, simply use from my_package import module_name.

Installing Third-Party Packages

Python’s ecosystem extends far beyond the standard library. A variety of third-party packages are available on the Python Package Index (PyPI). You can install these packages using pip, ensuring access to specialized tools and libraries for data analysis, web development, machine learning, and more.


# Installing a third-party package using pip
# In your terminal or command prompt, run:
pip install requests
        

Once installed, you can import and use these packages just like built-in modules: import requests. Keep track of your dependencies (e.g., using pip freeze) so others can reproduce your environment.

Creating Your Own Packages

You can distribute your own packages to share code with colleagues or the Python community. The Python Packaging User Guide explains how to structure your project, write a setup.py or pyproject.toml, and publish to PyPI. Even if you never publish publicly, packaging your code can simplify internal sharing and version management.


# Basic folder structure for a distributable package
# my_cool_project/
#     my_cool_package/
#         __init__.py
#         core.py
#         utils.py
#     setup.py
#     README.md
#     LICENSE
        

Prompting Generative AI for Identifying and Implementing the Right Packages

AI can guide your search for ideal packages or libraries. Instead of asking “Which packages do I need?” you might specify, “I need to parse and format dates in Python—what libraries or standard modules work for that?” Along with context—like advanced time zone handling—AI can suggest datetime or dateutil.

Example Prompt:
Generate a Python script that uses the 'dateutil' package to parse and format dates.

Resulting AI-generated code:


from dateutil import parser
from datetime import datetime

# Parsing a date string
date_str = "2024-05-27T10:30:00Z"
parsed_date = parser.parse(date_str)
print(f"Parsed date: {parsed_date}")

# Formatting the date
formatted_date = parsed_date.strftime("%B %d, %Y %H:%M:%S")
print(f"Formatted date: {formatted_date}")
        

This script shows how AI-generated examples can integrate directly into your development process—just remember to install dependencies like python-dateutil (via pip install python-dateutil) and review the generated code for correctness and security before using it in production.

Back to Home