Skip to contentSkip to navigation

Module 07 · Lesson 03

Modules and Packages

Reuse code across files: import modules from the standard library and your own project, choose between import styles, and guard a script's main code with __name__.

  • About 8 minutes
  • Builds on earlier lessons
  • 12-question quiz at the end

What you will learn

  • Three ways to import
  • Look inside a module
  • The main guard
  • Watch names arrive

Code from other files

A module is a Python file full of ready-made tools. `import` lets you use them.

  • import

    import math loads the module. Reach its tools with a dot: math.sqrt(16).

  • from ... import

    from math import pi brings in one name, so you can write pi on its own.

  • as

    import statistics as stats gives a long name a short nickname.

  • Your own

    Any .py file you write is a module. A folder of them is a package.

Modules everywhere

Python ships with hundreds of modules, and other people have written many more.

  • Gamesrandom rolls dice and shuffles cards.
  • Big appsLarge programs split their code into packages such as shop.cart and shop.payments.
  • Dates and timesdatetime knows today's date and how long until the weekend.
  • Your helpersWrite a helper once in helpers.py, then import it wherever you need it.

An import with a nickname

This line takes one function out of a module. Tap each part to see its job.

Part 1 of 6

Tap any part of the code below, or press Next.1 of 6 explored

from:Names the module to take something out of.

Use ready-made modules

Pick an example, change it, then press Run. Say what you expect to see before you press.

Example 1 of 6import

import loads a module. A dot reaches the tools inside it.

Your turn: Print math.pow(2, 10) and compare it with 2 ** 10.

Python
import math
print(math.sqrt(81))
print(math.pi)
print(math.floor(7.9), math.ceil(7.1))
Output
Press Run to see what it prints.

Watch names arrive

Press Step to run one line at a time. Watch the names box change.

Ready. Press Step to run the first line.

  1. import math
  2. from statistics import mean as average
  3. sides = [3, 4]
  4. long_side = math.sqrt(sides[0] ** 2 + sides[1] ** 2)
  5. avg = average(sides)
  6. print("long side", long_side)
  7. print("average", avg)

Output so far

Nothing printed yet.

What Python does

Python reads the program from the top. Nothing has run yet.

Names

None yet.

Quick guesses

Guess first, then read why. A wrong guess is where the learning happens. Nothing here is scored.

Question 1 of 6

1.Rounding a negative down:

import math
print(math.floor(-7.2))

0 of 6 answered

Common module misconceptions

Each card is something learners often believe. Tap it to see what Python really does.

Misconception 1 of 4

Notes

Everything above, in words. Open it when you want the full explanation.

Read the notesOpen

What a module is

A module is simply a Python file. Its functions, classes and variables become available to other code that imports it. Python's standard library is a collection of modules, such as math, random, datetime and json, that come with every installation.

Try it 1: edit me, then Run
import math

print(math.sqrt(81))      # 9.0
print(math.pi)            # 3.141592653589793
print(math.floor(4.7))    # 4
Output
Press Run to see what it prints.

import math runs the module once and creates a name math that refers to it. Everything inside is reached with dot notation: math.sqrt is the sqrt function that lives in math. Keeping the module name in front makes it clear where each tool came from, and avoids clashes: math.floor and a variable of your own called floor can live side by side.

Three import styles

Try it 2: edit me, then Run
import statistics                 # use as statistics.mean(...)
from statistics import mean       # use as mean(...)
import statistics as st           # use as st.mean(...)
Output
Press Run to see what it prints.

from module import name copies one name into your file, so you can call it without the prefix. You can import several at once: from math import sqrt, pi. import ... as ... gives the module a shorter alias; some aliases are so common that everyone uses them, such as import numpy as np in data science.

Which style should you pick? Plain import module is the safest default because every call shows its source. from ... import is fine for a few names you use often. Avoid from module import *, which dumps every public name into your file: you can no longer tell where a name came from, and an imported name can silently replace one of your own.

Imports run once

The first time a module is imported, Python finds the file, runs it top to bottom and stores the result. Importing it again anywhere in the program reuses that stored module; the file does not run a second time. That is why imports normally sit at the top of a file, all together, where readers expect them.

Your own modules

Any .py file you write can be imported by another file in the same folder. Suppose a project has two files:

Try it 3: edit me, then Run
# pricing.py
TAX_RATE = 0.2

def with_tax(price):
    return round(price * (1 + TAX_RATE), 2)
Output
Press Run to see what it prints.
Try it 4: edit me, then Run
# shop.py
import pricing

print(pricing.with_tax(10))       # 12.0
print(pricing.TAX_RATE)           # 0.2
Output
Press Run to see what it prints.

You import by the file name without .py. Do not name your own file after a standard module, such as random.py or math.py: Python finds your file first, and import random then imports your file instead of the real one, usually with a confusing AttributeError.

Packages

When a project has many modules, related ones are grouped into a folder called a package. A package folder usually contains a file named __init__.py, which runs when the package is first imported and is often empty.

shop/
    main.py
    payments/
        __init__.py
        cards.py
        refunds.py

From main.py you reach a module inside the package with dots: from payments import cards, or from payments.refunds import issue_refund. The dot in an import path means "inside", just as it does in math.sqrt.

The name guard

Every module has a variable called __name__. When you run a file directly, Python sets its __name__ to the string "__main__". When the same file is imported, __name__ is the module's own name instead, such as "pricing". This lets a file behave differently in the two situations:

Try it 5: edit me, then Run
def with_tax(price):
    return round(price * 1.2, 2)

if __name__ == "__main__":
    # Runs only when this file is run directly, not when imported.
    print(with_tax(10))
Output
Press Run to see what it prints.

Without the guard, importing pricing would also print, because importing runs the whole file. Put quick manual checks and the program's start-up code under the guard, and keep the reusable functions above it.

Exploring a module

dir(module) lists the names a module provides, and help(module.name) shows a function's documentation. Names starting with an underscore are meant for the module's own use. The official documentation at docs.python.org describes every standard module, and it is worth browsing: many problems you might solve by hand already have a tested solution there, from averaging numbers with statistics to counting things with collections.

Syntax

The general shape of the statements in this lesson.

syntax.py
import math                     # math.sqrt(9)
from math import sqrt, pi       # sqrt(9)
import statistics as st         # st.mean([1, 2])
from payments import cards      # module inside a package
from payments.cards import charge
if __name__ == "__main__":      # only when run directly
    main()
dir(math)                       # names a module offers
Output
Press Run to see what it prints.

Worked examples

Read the problem, run the code, then read why it works.

Example 1 of 2

Summarising test scores with statistics

Beginner

Report the mean, median and highest score of a class without writing the maths yourself.

Python
import statistics

scores = [72, 85, 90, 64, 85, 78]

print("Mean:", round(statistics.mean(scores), 1))
print("Median:", statistics.median(scores))
print("Most common:", statistics.mode(scores))
print("Highest:", max(scores))
Output
Press Run to see what it prints.

Predict first

How it works(open after your guess)

One import gives access to well-tested functions for averages. statistics.median sorts the scores and takes the middle, averaging the two middle values when there is an even count. max is a built-in, so it needs no import at all.

Common pitfalls

Mistakes people make with this topic, and what to write instead.

Pitfall 1 of 3

Forgetting the module prefix

Spot the bug

Can you see what is wrong? Run it to watch it go wrong, then open the fix.

Buggy code: run it
import math
print(sqrt(16))
Output
Press Run to see what it prints.
Show what goes wrong and the fix

What happens

NameError: name 'sqrt' is not defined

Write this instead

import math
print(math.sqrt(16))

Why it happens

import math creates only the name math. The function lives inside it as math.sqrt.

In the real world

Where this shows up in software people use every day.

  1. Splitting a bill with helper modules

    Hospitality

    A restaurant's till program uses the standard library for rounding and money maths instead of hand-written arithmetic, keeping the main program short.

    Why Python fits

    math.ceil rounds each share up to the next penny, so the restaurant never collects less than the bill. Importing mean by name keeps the tip line short, while math.ceil keeps its prefix because it is used only once.

    Python
    import math
    from statistics import mean
    
    bill = 87.40
    people = 3
    share = math.ceil(bill / people * 100) / 100
    print("Each pays:", share)
    print("Collected:", round(share * people, 2))
    
    tips = [5.0, 7.5, 4.0]
    print("Average tip:", round(mean(tips), 2))
    Output
    Press Run to see what it prints.

Key takeaways

Tick each one you could explain to a friend.

0 of 5

Common questions

Guess the answer first, then open it.

Where does Python look for modules?

First in the folder of the program you ran, then in the standard library, then in installed third-party packages. That search order is why a file of your own can hide a standard module.

How do I install modules that are not in the standard library?

Outside the browser you use pip, for example pip install requests. The PyLabs runner offers the standard library only.

Which standard modules are worth knowing first?

math and statistics for numbers, random for chance, datetime for dates, json and csv for data files, pathlib for paths and collections for counting and grouping. This course covers most of them in later lessons.

Does a package always need __init__.py?

Modern Python can import a folder without it, but adding one is still the clear, common convention, and it is the place for package start-up code.

Your notes

Sign in to keep private notes alongside this lesson.

Sign in to take notes

Where to go next

The quiz and the Lab live on their own pages, so this lesson stays about learning.

Finished this lesson?

Create an ID or sign in to save your progress across devices.

Create ID to save
Lessons done in this module0/3 complete
Quiz

Check what you learned

12 questions, with an explanation after every answer. A verified attempt counts towards opening the module Lab.

Lab

Keep going in the Lab

7 tasks on this lesson, from writing code to tracing it by hand. Practice only, no XP.

Review

Spaced review

Questions you miss in a quiz come back on a spaced schedule, so what you learned here sticks.

This lesson at a glance

The 8 lines of code this lesson uses, each with a short note. Keep it open while you do the quiz and the Lab.

What else you can search for and explore

Curious to go further? Each card opens a web search in a new tab.

References

Look things up here whenever you need the exact details.