Modules & Packages · Unit 5

Modules & Packages

import, from ... import and packages

Unit 5 · Reuse and organize code

Modules and packages give code a home

A module is a Python file containing reusable code. A package groups related modules in a directory. Importing lets your program use that code without copying it into every file.

Module

One .py file containing functions, values, or classes.

Import

A statement that makes module names available.

Package

A directory grouping related modules; __init__.py can define its public interface.

One module, two files

In a normal project, create these files and run main.py from the project folder. Pyodide’s shared runner executes one cell, so the runnable example combines the module definition and its use in order.

mymodule.py
def welcome(name):
    return f"Welcome, {name}!"

def double(value):
    return value * 2
main.py
from mymodule import welcome, double

print(welcome("Mira"))
print(double(21))
Two import styles: import mymodule then call mymodule.welcome(...); or from mymodule import welcome then call welcome(...). Avoid from mymodule import * because it hides where names came from.
Run the example in one browser cell
Starting up Python…
# Equivalent one-cell demo: mymodule.py first
def welcome(name):
    return f"Welcome, {name}!"

def double(value):
    return value * 2

# main.py uses the module functions
print(welcome("Mira"))
print(double(21))
The editor is ready while Python loads in the background.

Output

Your program's output will appear here.
Common Python mistakes

NameError: name 'mark' is not defined

NameError: A name was used before Python could find a variable or function with that name.

IndexError: list index out of range

IndexError: The requested position is outside the items in this list or sequence.

KeyError: 'email'

KeyError: That key does not exist in this dictionary.

TypeError: can only concatenate str (not "int") to str

TypeError: This operation does not work with the kind of value it received.

ZeroDivisionError: division by zero

ZeroDivisionError: A number cannot be divided by zero.

SyntaxError: invalid syntax

SyntaxError: Python could not understand the structure of this line. Check spelling, brackets, colons, and quotes.

IndentationError: expected an indented block

IndentationError: The spaces at the start of a line do not match Python's block structure.

Packages group modules by purpose

A package directory may contain __init__.py and several modules. The initializer can be empty or expose selected names. Import paths follow the folder structure.

Project tree
school_tools/
  __init__.py
  marks.py
  names.py
main.py
school_tools/marks.py
def average(values):
    return sum(values) / len(values)
main.py
from school_tools.marks import average

print(average([82, 91, 76]))

The dots in school_tools.marks mean “module marks inside package school_tools.” This structure helps as a program grows; a tiny one-file script does not need a package.

Package import pattern
Starting up Python…
# Single-cell equivalent of school_tools/marks.py
def average(values):
    return sum(values) / len(values)

# Equivalent to importing average from school_tools.marks
print(round(average([82, 91, 76]), 1))
The editor is ready while Python loads in the background.

Output

Your program's output will appear here.
Common Python mistakes

NameError: name 'mark' is not defined

NameError: A name was used before Python could find a variable or function with that name.

IndexError: list index out of range

IndexError: The requested position is outside the items in this list or sequence.

KeyError: 'email'

KeyError: That key does not exist in this dictionary.

TypeError: can only concatenate str (not "int") to str

TypeError: This operation does not work with the kind of value it received.

ZeroDivisionError: division by zero

ZeroDivisionError: A number cannot be divided by zero.

SyntaxError: invalid syntax

SyntaxError: Python could not understand the structure of this line. Check spelling, brackets, colons, and quotes.

IndentationError: expected an indented block

IndentationError: The spaces at the start of a line do not match Python's block structure.

Built-in numeric module: math

Functions such as abs() are built-ins. Math functions belong to the math module, so import it and use dot notation.

math.sqrt(x)

Square root; x must be non-negative.

math.ceil(x)

Round up to the nearest integer.

math.floor(x)

Round down to the nearest integer.

math.factorial(n)

Factorial of a non-negative integer.

math.pi

Approximation of π.

math.gcd(a, b)

Greatest common divisor.

math.sqrt

Square root of a non-negative number

Expected result: 9.0

Try math.sqrt
Starting up Python…
import math
print(math.sqrt(81))
The editor is ready while Python loads in the background.

Output

Your program's output will appear here.
Common Python mistakes

NameError: name 'mark' is not defined

NameError: A name was used before Python could find a variable or function with that name.

IndexError: list index out of range

IndexError: The requested position is outside the items in this list or sequence.

KeyError: 'email'

KeyError: That key does not exist in this dictionary.

TypeError: can only concatenate str (not "int") to str

TypeError: This operation does not work with the kind of value it received.

ZeroDivisionError: division by zero

ZeroDivisionError: A number cannot be divided by zero.

SyntaxError: invalid syntax

SyntaxError: Python could not understand the structure of this line. Check spelling, brackets, colons, and quotes.

IndentationError: expected an indented block

IndentationError: The spaces at the start of a line do not match Python's block structure.

Import with care

NameError

Calling sqrt(81) without importing it

Use math.sqrt(81), or explicitly import sqrt from math.

Name shadowing

Naming your own file math.py

Python may import your file instead of the standard library module. Choose a descriptive filename.

Import location

Running a script from an unexpected folder

Python searches known locations. Organize project files and run from the project root.

Wildcard imports

from math import *

This adds many names and can cause collisions. Import the module or selected names explicitly.

Check your understanding

1. What is a Python module?

2. Which call accesses sqrt through the math module?

3. What is __init__.py commonly used for?