Modules and Imports
As your Python programs grow larger, you’ll need to split your code across multiple files. Modules let you organize related code into separate files. The import system lets you use that code in other parts of your program. Together, they form the foundation for building maintainable Python applications.
In this tutorial, you’ll learn how to create your own modules, understand how Python finds and loads them, use the various import statements effectively, and start exploring the vast standard library that comes with Python.
What Is a Module?
A module is simply a Python file containing definitions and statements. The filename (without the .py extension) becomes the module’s name. When you import a module, Python executes all the code in that file and makes its contents available.
Create a file called greeting.py with this content:
def say_hello(name):
return f"Hello, {name}!"
def say_goodbye(name):
return f"Goodbye, {name}!"
Now you can import this module in another file or in the Python interpreter:
import greeting
message = greeting.say_hello("Alice")
print(message) # Hello, Alice!
The module name (greeting) becomes a namespace that holds all the definitions from that file. This keeps your code organized and prevents name conflicts.
The Import Statement
Python offers several ways to import modules and their contents. Each approach has its use cases.
The Basic Import
The most common form imports the entire module:
import math
result = math.sqrt(16)
print(result) # 4.0
This approach keeps the original namespace intact. You always know where each function comes from.
Importing Specific Items
Use from ... import to bring specific names directly into your namespace:
from math import sqrt, pi
result = sqrt(16)
print(result) # 4.0
print(pi) # 3.141592653589793
This is useful when you only need a few items from a large module.
Aliasing
You can rename imported items using as. This helps avoid name conflicts or create shorter names:
import numpy as np
import tensorflow as tf
arr = np.array([1, 2, 3])
The Star Import
You can import everything from a module using from module import *:
from math import *
result = sqrt(16)
print(pi)
Avoid this in production code. It fills your namespace with unknown names, making it hard to track where things come from. It also silently overwrites existing names. Use it only for quick interactive experiments.
The Module Search Path
When you write import something, Python needs to find the file. It searches in a specific order, stored in sys.path:
- The current directory (or the directory containing the script)
- Directories listed in the
PYTHONPATHenvironment variable - The standard library directories
- Site packages (where third-party libraries are installed)
You can see your current search path:
import sys
for path in sys.path:
print(path)
This matters when you’re debugging import errors. If Python can’t find your module, check that the file exists in one of these locations or that your current working directory is correct.
Running Modules as Scripts
Every Python file has a special variable called __name__. When you run a file directly, __name__ equals "__main__". When you import it, __name__ equals the module name.
This lets you use the same file as both a module and a standalone script:
# greeting.py
def say_hello(name):
return f"Hello, {name}!"
if __name__ == "__main__":
# This runs when the file is executed directly
print(say_hello("World"))
Run it directly:
python greeting.py
# Output: Hello, World!
Import it from another file:
import greeting
print(greeting.say_hello("Alice"))
# Output: Hello, Alice!
This pattern is essential for creating reusable modules that also work as command-line tools.
Exploring Module Contents
The dir() function lists everything defined in a module:
import math
print(dir(math))
# ['__doc__', '__loader__', '__name__', '__package__',
# 'acos', 'acosh', 'asin', 'asinh', 'atan', ...]
This is useful for discovering what’s available in unfamiliar modules.
Packages: Directories of Modules
A package is a directory containing an __init__.py file, along with Python modules. Packages let you organize related modules into a hierarchy.
Create this structure:
my_package/
__init__.py
utils.py
helpers/
__init__.py
data.py
Each __init__.py can be empty or contain initialization code:
# my_package/__init__.py
from .utils import process_data
from .helpers.data import load_file
__all__ = ["process_data", "load_file"]
Now you can import using dot notation:
from my_package import process_data
from my_package.helpers.data import load_file
The __init__.py file can also expose specific items from submodules:
# my_package/helpers/__init__.py
from .data import load_file, save_file
__all__ = ["load_file", "save_file"]
The Standard Library at Your Fingertips
Python ships with a massive standard library. You don’t need to install anything extra to work with files, dates, web data, compression, and much more.
Here are some commonly used modules:
import os # File and directory operations
import json # JSON parsing and serialization
import datetime # Date and time handling
import re # Regular eyÀressions
import collections # Specialized container datatypes
import itertools # Iterator functions
The standard library is one of Python’s greatest strengths. Before writing code from scratch, check if the standard library has what you need.
Common Import Patterns
Here’s what professional Python code typically looks like:
# Standard library imports
import os
import sys
import json
from pathlib import Path
# Third-party imports
import requests
from flask import flash
# Local application imports
from .models import User
from .utils import format_date
Grouping imports this way makes it clear where each dependency comes from.
Next Steps
You now understand how to organize code into modules and packages, and how to import what you need. These skills let you build larger applications without everything getting tangled together.
Continue your learning journey with the next tutorial in the series: Classes and Objects â where you’ll learn about object-oriented programming in Python.