Chapter 14

Modules and Libraries

Discover how to reuse code with import and the wider Python library ecosystem.

What is a Module?

A module is simply a file of Python code that you can reuse. Instead of writing everything yourself, you can bring in ready-made code with the import keyword. A library is a collection of related modules.

The Standard Library

Python ships with a large standard library that is already installed. Popular modules include math for numbers, random for randomness, and datetime for dates and times.

import math
print(math.sqrt(9))    # 3.0
print(math.floor(4.7)) # 4
print(math.pi)         # about 3.14159

Different Ways to Import

You can import a whole module and use dot notation, or import a specific name with the from form, or give a module a short alias with as.

import random
print(random.randint(1, 1))   # always 1

from math import sqrt
print(sqrt(16))               # 4.0

import statistics as st
print(st.mean([2, 4, 6]))     # 4

The randint function includes both end numbers, so randint(1, 1) can only be 1.

Installing External Libraries

Some libraries are not part of the standard library. You install these extra packages using the pip tool from the command line, for example writing pip install followed by the package name. Well-known external libraries include requests for web requests and pandas for data.

Why Use Modules?

  • They save time by reusing tested code.
  • They keep your own files short and tidy.
  • They let many programs share the same helpful tools.

Writing Your Own Module

Any Python file you create is itself a module. If you save some functions in a file called helpers.py, another file in the same folder can use them by writing import helpers and then calling helpers followed by a dot and the function name. This is how large projects split their work across many tidy files instead of one giant file.

import helpers
print(helpers.greet('Sara'))

When you import a module, Python runs it once and remembers it, so later imports of the same module are fast. Choosing good module names and importing only what you need keeps a program easy to read and easy for your teammates to follow.

Remember

  • A module is a reusable file of Python code.
  • Use import to bring a module into your program.
  • The from keyword imports one specific name.
  • The as keyword gives a module a short alias.
  • Use pip to install libraries that are not built in.

Stuck on this topic? A verified JomKelas tutor can walk you through it.

Find a verified tutor