🎉 Welcome to PyVerse! Start Learning Today

Modules and Packages

1) What are Modules and Packages?

  • Module: A single Python file that contains code you can reuse (functions, variables, classes). Example: math.py in the standard library.
  • Package: A folder that groups related modules together. It helps you organize bigger projects.

Why use them?

  • Keep code organized and readable
  • Reuse code across projects
  • Work in teams without stepping on each other's toes

2) Using Modules (Imports)

Basic imports:

  • import math
    • Use with dot notation: math.sqrt(16), math.pi
  • import math as m
    • Use alias to shorten names: m.sqrt(25)
  • from math import sqrt, pi
    • Import specific names: sqrt(81), pi
  • Avoid: from math import *
    • It can cause name clashes and confusion.

Examples:

1) Basic math module

import math print(math.sqrt(16)) # 4.0 print(math.pi) # 3.1415926535...

2) Aliases

import random as rnd print(rnd.randint(1, 6)) # Simulate a dice roll

3) Importing specific names

from datetime import date, timedelta today = date.today() tomorrow = today + timedelta(days=1) print("Today:", today, "Tomorrow:", tomorrow)

3) Helpful Standard Library Modules

  • math: math.sqrt, math.pi, math.ceil
  • random: random.randint, random.choice, random.shuffle
  • datetime: datetime.date, datetime.timedelta
  • os and pathlib: Work with files and folders
  • statistics: statistics.mean, statistics.median

Examples:

1) random choices

import random students = ["Amir", "Bea", "Chen", "Dina"] leader = random.choice(students) print("Leader:", leader)

2) statistics

import statistics as stats scores = [78, 85, 90, 92, 88] print("Average:", stats.mean(scores)) print("Median:", stats.median(scores))

4) Creating Your Own Module

Step 1: Make a file named greetings.py

def hello(name): return f"Hello, {name}!" def excited(message): return message.upper() + "!!!" # This code runs only when you run greetings.py directly, not when imported if __name__ == "__main__": print(hello("Tester")) print(excited("modules are cool"))

Step 2: Use it in main.py (same folder)

import greetings print(greetings.hello("PyVerse")) print(greetings.excited("we made a module"))

You can also import specific functions:

from greetings import hello print(hello("class"))

Where does Python look for modules?

  • The current folder (where your script runs)
  • Installed site-packages (things you install with pip)
  • System paths listed in sys.path

5) Packages: Organizing Multiple Modules

A package is a folder that contains related modules. You can add a special file named __init__.py to mark it as a package and control what's exposed. In modern Python, __init__.py is optional, but it's still common to include it.

Example package structure:

mytools/ __init__.py geometry.py statsplus.py

geometry.py

import math def circle_area(r): return math.pi * r * r def rectangle_area(w, h): return w * h

statsplus.py

def average(nums): return sum(nums) / len(nums) if nums else 0

__init__.py

# Expose selected functions at the package level from .geometry import circle_area, rectangle_area from .statsplus import average

Using the package in main.py (placed next to the mytools folder):

from mytools import circle_area, average print(circle_area(5)) print(average([10, 20, 30]))

Relative imports inside a package:

  • Use a leading dot to import from the same package
  • Example inside statsplus.py: from .geometry import circle_area

6) Installing Third-Party Packages (Just a peek)

  • Use pip to install extra packages from the internet:
    • pip install requests
  • Then import them in your code:
    • import requests
  • For this lesson, we'll stick to standard library and our own code.

Mini Project: Build Your Own SchoolTools Package

Goal: Create a package that helps with grades and schedules.

Folder structure:

schooltools/ __init__.py gradebook.py schedule.py main.py

1) gradebook.py

def average(scores): return sum(scores) / len(scores) if scores else 0 def letter_grade(score): if score >= 90: return "A" if score >= 80: return "B" if score >= 70: return "C" if score >= 60: return "D" return "F"

2) schedule.py

def format_schedule(schedule_dict): # schedule_dict example: {"Mon": ["Math", "Art"], "Tue": ["Science"]} lines = [] for day, classes in schedule_dict.items(): line = f"{day}: " + ", ".join(classes) if classes else f"{day}: (no classes)" lines.append(line) return "\n".join(lines)

3) __init__.py

from .gradebook import average, letter_grade from .schedule import format_schedule

4) main.py (next to the schooltools folder)

from schooltools import average, letter_grade, format_schedule scores = [85, 92, 78, 88] avg = average(scores) print("Average:", round(avg, 2)) print("Letter:", letter_grade(avg)) my_schedule = { "Mon": ["Math", "History"], "Tue": ["Science", "PE"], "Wed": ["Art"], "Thu": ["Computers", "English"], "Fri": [] } print() print("My Schedule:") print(format_schedule(my_schedule))

Try it:

  • Run main.py
  • You should see the average, the letter grade for that average, and a neatly formatted schedule.

Challenge ideas:

  • In gradebook.py, add a function highest(scores) and lowest(scores)
  • In schedule.py, add a function next_class(day, now_index) that returns the next class
  • Update __init__.py to export your new functions
  • Write simple tests under if __name__ == "__main__": in each module

Summary

  • A module is a single Python file; a package is a folder of modules.
  • Import modules with import moduleimport module as alias, or from module import name.
  • Prefer importing specific names or using aliases to keep code clear.
  • Create your own modules by writing functions in a .py file and importing them.
  • Packages organize larger projects; __init__.py lets you control what's exposed.
  • Practice by building small, useful packages and importing them in a main script.

You just leveled up your code organization skills. Next time your project grows, you'll know exactly how to keep it tidy and reusable!

Loading quizzes...