Learn Python Β· 10/15

Modules and Packages: Organizing Code

7 min read

Modules and Packages: Organizing Code PYTHON

Hey there! Welcome to the world of Python modules and packages. 🐍

Ever tried to build a massive LEGO castle with all the bricks jumbled in one giant box? It's chaotic, right? Finding that one specific tiny piece you need becomes a treasure hunt. That's what coding can feel like without a good way to organize your work. As your projects grow from a few lines to hundreds or even thousands, keeping everything in a single file becomes a recipe for disaster.

That's the problem we are here to solve. We need a way to neatly arrange our code into logical, reusable chunks. In Python, the solution is modules and packages. They are like the labeled storage drawers for your LEGOs, making your code clean, easy to manage, and shareable.


1. Importing Built-in Modules (math, datetime, random) 🎲

The Problem: Imagine you need to calculate the square root of a number, get the current date and time, or pick a random number. You could try to write the code for these tasks from scratch, but that would be like reinventing the wheel every time you need to drive. It's time-consuming and prone to errors.

The Solution: Python comes with a vast standard library, which is a collection of pre-written code organized into modules. A module is simply a file containing Python definitions and statements. By importing these modules, you gain instant access to a powerhouse of functions and data.

Let's look at some of the most frequently used built-in modules.

The math Module πŸ“

Need to do some serious number crunching? The math module is your best friend.

To use it, you first need to import it:

python
import math

Now, you have access to a variety of mathematical functions. To use a function from the module, you type the module's name, a dot (.), and then the function name.

Example:

python
# Calculate the square root of a number
sqrt_of_16 = math.sqrt(16)
print(f"The square root of 16 is: {sqrt_of_16}")

# Calculate the value of Pi
print(f"The value of Pi is: {math.pi}")

# Round a number up to the nearest integer (ceiling)
print(f"Ceiling of 4.2 is: {math.ceil(4.2)}")

# Round a number down to the nearest integer (floor)
print(f"Floor of 4.9 is: {math.floor(4.9)}")

The datetime Module πŸ“…

Working with dates and times is a common task, and the datetime module makes it a breeze.

Example:

python
import datetime

# Get the current date and time
now = datetime.datetime.now()
print(f"Current date and time: {now}")

# Get just the current date
today = datetime.date.today()
print(f"Today's date: {today}")

# You can also format the date into a more readable string
formatted_date = now.strftime("%Y-%m-%d %H:%M:%S")
print(f"Formatted date and time: {formatted_date}")

The random Module 🎰

Need a bit of unpredictability? The random module is perfect for games, simulations, or just shuffling a list.

Example:

python
import random

# Generate a random integer between 1 and 10 (inclusive)
random_number = random.randint(1, 10)
print(f"A random number between 1 and 10: {random_number}")

# Pick a random element from a list
fruits = ["apple", "banana", "cherry"]
random_fruit = random.choice(fruits)
print(f"A random fruit from the list is: {random_fruit}")

# Shuffle a list in place
deck_of_cards = ["Ace", "King", "Queen", "Jack"]
random.shuffle(deck_of_cards)
print(f"The shuffled deck is: {deck_of_cards}")

✨ Fun Fact: The "random" numbers generated by computers are not truly random! They are pseudo-random, meaning they are generated by a deterministic algorithm that produces a sequence of numbers that appears random. For most everyday purposes, this is perfectly fine.


2. Creating Your Own Modules πŸ› οΈ

The Problem: As your project grows, you'll likely have functions and variables that are related to each other. Keeping them all in one giant file makes it hard to navigate and reuse your code in other projects.

The Solution: You can create your own modules! It's surprisingly simple. Any Python file (.py) can be a module.

Let's imagine you are building a simple e-commerce application. You might have several functions for handling calculations.

Step 1: Create a file named calculations.py

This file will be our module. Let's add some functions to it.

python
# calculations.py

def calculate_tax(price, tax_rate):
  """Calculates the tax for a given price."""
  return price * tax_rate

def calculate_shipping(weight, rate_per_kg):
  """Calculates the shipping cost based on weight."""
  return weight * rate_per_kg

Step 2: Create a main file to use your module

Let's create another file named main.py in the same directory.

python
# main.py

import calculations

item_price = 100
tax = calculations.calculate_tax(item_price, 0.07)
shipping = calculations.calculate_shipping(2.5, 5)

total_cost = item_price + tax + shipping

print(f"Item Price: ${item_price}")
print(f"Tax: ${tax}")
print(f"Shipping: ${shipping}")
print(f"Total Cost: ${total_cost}")

And that's it! You've successfully created and used your own module. By separating your calculation logic into its own file, your main.py is cleaner and the calculations module can be reused in other parts of your application or even in different projects.


3. Packages: Structuring Multi-File Projects πŸ“¦

The Problem: Modules are great for organizing code into separate files. But what happens when your project gets even bigger? You might have dozens or even hundreds of modules. Just throwing them all into one folder can get messy again.

The Solution: This is where packages come in. A package is essentially a directory of modules. It allows you to create a hierarchical structure for your codebase.

Think of it like this: if a module is a single document, a package is a folder that can contain multiple documents and even other folders (sub-packages).

To turn a directory into a Python package, it needs to contain a special file called __init__.py. This file can be empty, but its presence tells Python that the directory is a package.

Example of a Package Structure:

Let's expand our e-commerce application. We might have functionalities for user management and payments. A good package structure would look like this:

stylus
ecommerce/
β”œβ”€β”€ __init__.py
β”œβ”€β”€ payments/
β”‚   β”œβ”€β”€ __init__.py
β”‚   └── process_payment.py
└── users/
    β”œβ”€β”€ __init__.py
    └── manage_users.py
main.py

Here, ecommerce is our main package, and it contains two sub-packages: payments and users. Each of these has its own __init__.py file and a module.

Now, from main.py, you can import and use functions from these modules using dot notation:

python
# main.py

from ecommerce.users import manage_users
from ecommerce.payments import process_payment

user = manage_users.create_user("testuser", "password123")
process_payment.charge_credit_card(user, 100.00)

This structure makes your project much more scalable and organized.


4. Installing Third-Party Packages with pip πŸš€

The Problem: The Python standard library is extensive, but it can't do everything. What if you need to work with web requests, advanced data analysis, or image processing? You don't want to build these complex tools from scratch.

The Solution: The Python community has created a massive ecosystem of third-party packages that you can easily install and use. The tool to do this is called pip, which stands for "Pip Installs Packages" (a recursive acronym!). pip is the standard package installer for Python.

These packages are hosted on the Python Package Index (PyPI), a vast repository of software for the Python programming language.

How to Use pip

pip is a command-line tool. You'll use it in your terminal or command prompt, not in your Python script.

The most common command is pip install:

sh
pip install package_name

Example: Installing the requests package

The requests library is a very popular package for making HTTP requests. To install it, you would open your terminal and type:

sh
pip install requests

Once installed, you can import and use it in your Python code just like a built-in module:

python
import requests

response = requests.get('https://api.github.com')

if response.status_code == 200:
  print('Successfully fetched the page!')
  # print(response.json()) # You can even get the JSON response directly
else:
  print('Something went wrong!')

Finding Packages:

You can search for packages on the PyPI website. Each package page usually has documentation and examples of how to use it.

✨ Industry Practice: It's a very common practice to manage your project's dependencies (the third-party packages it uses) in a file called requirements.txt. This file simply lists the packages and their versions. You can then install all the dependencies for a project with a single command: pip install -r requirements.txt. This makes it easy for other developers to set up the same environment.

By mastering modules and packages, you're taking a huge step towards writing clean, organized, and professional Python code. Happy coding! 😊


πŸ“š References for Extra Reading

Challenge

You are a developer working on an e-commerce platform. Your task is to write a script that processes an order summary. The project has a pre-defined package structure which you must work with.

Project Structure:

vim
shop/
β”œβ”€β”€ __init__.py
β”œβ”€β”€ products/
β”‚   β”œβ”€β”€ __init__.py
β”‚   └── inventory.py
└── utils/
    β”œβ”€β”€ __init__.py
    └── formatting.py
  • The shop/products/inventory.py module contains a function: check_stock(product_id: str) -> bool.
  • The shop/utils/formatting.py module contains a function: format_price(price: float) -> str.

Your Goal:

Complete the main.py script by implementing the following:

  1. From the shop.products.inventory module, import the check_stock function directly.
  2. Import the entire shop.utils.formatting module, giving it the alias fmt.
  3. Import the standard built-in datetime module.
  4. Inside the generate_order_summary function, implement the logic to:
    • Call check_stock() to see if an item is available.
    • If it is available, get the current timestamp using datetime.datetime.now(), format the price using the fmt module, and return a string in the format: "Order for {product_id} placed at {timestamp}. Price: {formatted_price}".
    • If it is not available, return the string: "Product {product_id} is out of stock."

Expected result

Your final code should contain the correct import statements for check_stock, shop.utils.formatting as fmt, and datetime. The generate_order_summary function must be fully implemented according to the instructions, correctly calling the imported functions and using the datetime module to produce the required output string depending on stock availability.

An example of a correct implementation would be:

python
from shop.products.inventory import check_stock
import shop.utils.formatting as fmt
import datetime

def generate_order_summary(product_id: str, price: float) -> str:
    """
    Checks stock, gets a timestamp, formats the price, and generates an order summary string.
    """
    if check_stock(product_id):
        timestamp = datetime.datetime.now()
        formatted_price = fmt.format_price(price)
        return f"Order for {product_id} placed at {timestamp}. Price: {formatted_price}"
    else:
        return f"Product {product_id} is out of stock."
python

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.