What Are Modules?
A module is a Python file containing code you can reuse in your programs, such as functions and variables.
Instead of writing everything yourself, you can import code that someone has already written and use it in your program.
Python modules help you keep your code organized and avoid rewriting the same functionality.
There are two main categories we’ll look at:
- Standard library modules: Modules that ship with Python, so you don’t need to install them separately.
- Third-party modules: Modules provided by others that you usually need to install separately.
Let’s start with Python’s standard library.
The Standard Library
Python comes with many modules that provide ready-made functionality.
Here are a few examples:
| Module | What it’s used for |
|---|---|
| random | Generating random values |
| math | Mathematical operations |
| datetime | Working with dates and times |
How to Import a Module
To use a module, you generally import it with the import keyword.
For example, let’s use Python’s math module:
import math
result = math.sqrt(9)
print(result)
# Output:
# 3.0Here’s what’s happening:
import mathmakes the module available in our code.math.sqrt(9)calls thesqrt()function from themathmodule.sqrt()calculates the square root of a number.- The result is
3.0.
Notice that we write math.sqrt(), not just sqrt(). The math. part tells Python which module the function belongs to.
You can also explore what a module contains using dir() and read about a function using help():
import math
print(dir(math)) # This prints a long list
help(math.sqrt)dir(math) lists names available in the module, while help(math.sqrt) displays documentation about the function.
Importing a Module With an Alias
Sometimes, developers use a shorter name for a module. This is called an alias.
You can create an alias using as.
For example:
import math as m
result = m.sqrt(25)
print(result)
# Output:
# 5.0Here, m is an alias for math.
Instead of writing math.sqrt(25), we can write m.sqrt(25).
Both versions work the same way.
Aliases are useful when a module has a long name or when a commonly used alias is part of a library’s convention.
Importing Specific Functions
You don’t always need to import an entire module. You can import a specific function using from ... import ....
For example:
from math import sqrt
print(sqrt(36))
# Output:
# 6.0Because we imported sqrt directly, we can call it without writing math. before it.
Compare the two approaches:
import math
print(math.sqrt(36))And:
from math import sqrt
print(sqrt(36))Both produce the same result.
You may also see this syntax:
from math import *It imports many names from a module directly, but it’s generally discouraged because those names can overwrite variables or functions in your own code.
For now, using import math is a good way to keep track of where a function comes from.
Your Own Python Module
So far, we’ve imported modules that Python or other developers have already created.
But remember, a module is simply a Python file containing reusable code. You can create one yourself!
Let’s say you want to reuse a greeting function in different programs.
Create a file named greetings.py:
# greetings.py
def say_hello(name):
print("Hello", name)Now create another file named main.py in the same folder:
# main.py
import greetings
greetings.say_hello("Shefali")
# Output:
# Hello ShefaliHere’s what happens:
greetings.pycontains oursay_hello()function.import greetingsmakes that module available inmain.py.greetings.say_hello("Shefali")calls the function from our module.
To see the output, run main.py, not greetings.py. The greetings.py file only defines the function, while main.py imports and calls it.
That’s it! You’ve created your own module and reused code from it.
Avoid naming your Python files after modules you’re trying to import. For example, don’t name your file random.py or math.py. Python might import your file instead of the actual standard library module, leading to confusing errors.
Third-Party Modules
Python also has a huge ecosystem of third-party packages that provide additional functionality.
Some examples are:
| Package | What it’s used for |
|---|---|
| pandas | Working with and analyzing data |
| numpy | Numerical calculations and arrays |
| tensorflow | Machine learning |
Unlike standard library modules such as math, these packages generally need to be installed separately before you can use them.
Let’s see how the process works.
Installing a Package
Python commonly uses a tool called pip to install packages.
For example, to install numpy, run this command in your terminal:
python3 -m pip install numpyAfter installation, you can import and use it:
import numpy as np
arr = np.array([1, 2, 3, 4])
print(arr)
# Output:
# [1 2 3 4]Here, np is a commonly used alias for numpy.
One thing to remember: pip install numpy is a terminal command, not Python code. Run it in your terminal, then use import numpy in your Python file.
What If You Forget to Install a Package?
If you try to import numpy before installing it, you may see this error:
import numpy
# ModuleNotFoundError: No module named 'numpy'If you see this error, the module isn’t installed in the Python environment you’re using. Run the pip command first, then try importing it again.
You may see a similar error if Python can’t find a module you’re trying to import.
You can explore other modules and packages by reading their documentation to understand how to use them.
A Quick Note About Modules and Packages
You’ll often hear the words module, package, and library used when working with Python.
For now, remember this simple distinction:
- A module is a Python file containing reusable code.
- A package organizes related modules together.
- A library is a broader collection of reusable code.
You’ll explore these terms further as you work with more Python tools.
👉 Next tutorial: Python String Formatting