Modules
Learn what a module is, the different ways to import code in Python, the __name__ == "__main__" idiom, and how Python locates modules.
Introduction
As programs grow, keeping everything in a single file becomes messy and hard to maintain. Python solves this with modules — a simple way to split code across multiple files and reuse it wherever it is needed.
In this lesson, you will learn exactly what a module is, the different ways to import one, a very important idiom every Python script should know, and how Python actually locates the modules you import.
- What a module is, in the simplest possible terms.
- How to use import, from...import, and import...as.
- The if __name__ == "__main__": idiom and why it matters.
- A few of Python's most useful built-in modules.
- How Python searches for modules using sys.path.
What is a Module?
A module is simply any Python file with a .py extension. That's the whole definition — every .py file you write is already a module the moment it exists. Modules let you organize related functions, classes, and variables into separate files, and then reuse that code by importing it elsewhere.
Just a .py File
Any file ending in .py can be treated as a module and imported elsewhere.
Reusable Code
Write a function once in a module, then use it in many different scripts.
Better Organization
Splitting code into modules keeps related logic grouped and files smaller.
Building Block for Packages
Modules are the foundation packages are built from, covered in the next lesson.
Creating Your Own Module
Imagine you have a file named greetings.py containing a couple of reusable functions.
def say_hello(name):
return f"Hello, {name}!"
def say_goodbye(name):
return f"Goodbye, {name}!"That file is now a module named greetings. As long as another Python file is in the same folder (or Python can otherwise locate it), it can import and use these functions.
import greetings
print(greetings.say_hello("Maya"))
print(greetings.say_goodbye("Maya"))Hello, Maya!
Goodbye, Maya!import module
The most common way to use a module is a plain import statement. This makes the entire module available, and you access its contents using dot notation: module.name.
import math
print(math.sqrt(16))
print(math.pi)4.0
3.141592653589793Everything inside the math module is accessed through the math. prefix, which keeps it clear exactly where each function or value came from.
from module import name
If you only need one or two specific things from a module, you can import them directly by name, without needing the module prefix afterward.
from math import sqrt, pi
print(sqrt(25))
print(pi)5.0
3.141592653589793You can also import everything from a module using from module import *, but this is generally discouraged because it makes it unclear where each name came from, and it can silently overwrite names already in your file.
from module import * pulls every public name into your file at once. This can cause naming collisions and makes code much harder to read and debug. Prefer importing specific names, or importing the whole module.
import module as alias
Sometimes a module name is long, or clashes with something else you are using. You can give it a shorter alias with the as keyword.
import datetime as dt
today = dt.date.today()
print(today)2026-07-25Aliasing is extremely common with certain well-known third-party libraries, such as import pandas as pd or import numpy as np, which you will encounter in later, more advanced lessons.
The if __name__ == "__main__": Idiom
Every Python module has a built-in variable called __name__. When a file is run directly, Python sets __name__ to "__main__". When that same file is imported by another file instead, __name__ is set to the module's actual name.
def add(a, b):
return a + b
print(f"This module's __name__ is: {__name__}")
if __name__ == "__main__":
print("Running calculator.py directly")
print(add(2, 3))This module's __name__ is: __main__
Running calculator.py directly
5import calculator
print(calculator.add(10, 20))This module's __name__ is: calculator
30Notice that the "Running calculator.py directly" line never printed in the second example. This idiom lets a file contain test code or a demo that only runs when the file is executed directly — not when it is imported as a module elsewhere.
- It lets a file work both as a reusable module and as a standalone script.
- It prevents demo/test code from running unexpectedly when a module is imported.
- It is considered standard practice in almost every real Python project.
Built-in Modules
Python ships with a large standard library of built-in modules that are always available, with no installation required. You have already seen math and datetime above — here is a quick look at a few commonly used ones. Each gets its own full lesson later in this course.
math
Mathematical functions and constants like sqrt(), floor(), and pi.
random
Generate random numbers, shuffle lists, and make random choices.
datetime
Work with dates, times, and time differences.
os
Interact with the operating system — files, directories, and paths.
json
Convert between Python objects and JSON text.
sys
Access interpreter-level details like command-line arguments and sys.path.
import random
print(random.randint(1, 6)) # simulate a dice roll4How Python Finds Modules
When you write import something, Python needs to locate the actual file. It searches a list of locations stored in sys.path, in order, and uses the first matching module it finds.
import sys
for location in sys.path:
print(location)
C:\Users\you\project
C:\Python312\Lib
C:\Python312\Lib\site-packagessys.path Typically Includes, in Order
- The directory containing the script being run (often shown as an empty string).
- Directories listed in the PYTHONPATH environment variable, if set.
- Python's standard library directories.
- Site-packages, where installed third-party packages live.
This is why a module you create in the same folder as your script can be imported immediately — that folder is automatically part of the search path.
Common Mistakes
- Naming your own file the same as a standard module (e.g., math.py), which can shadow the real module.
- Using from module import * and losing track of where names came from.
- Forgetting the if __name__ == "__main__": guard and having demo code run on every import.
- Assuming a module will always be found without checking it is in the same folder or an installed package.
- Importing an entire large module just to use one small function, when a specific import would be clearer.
Best Practices
- Keep related functions and classes together in a clearly named module.
- Prefer specific imports (from module import name) over wildcard imports.
- Always wrap script-only code in if __name__ == "__main__":.
- Use short, conventional aliases only for well-known libraries.
- Avoid naming your files the same as Python's built-in modules.
Frequently Asked Questions
Is every .py file automatically a module?
Yes. Any Python file can be imported as a module by another file, as long as Python can locate it.
What is the difference between import module and from module import name?
import module gives you the whole module, accessed with module.name. from module import name brings a specific name directly into your file, without needing the module prefix.
Why does __name__ equal "__main__" sometimes and the module name other times?
Python sets __name__ to "__main__" only when a file is executed directly. When that file is imported elsewhere, __name__ becomes the module's actual name instead.
Do I need to install modules like math or random?
No. These are part of Python's standard library and are built in — no installation needed. Third-party modules, covered in the pip lesson, do need to be installed.
What happens if two modules are in different folders?
Python may not find one unless its folder is on sys.path. Packages, covered in the next lesson, and installed libraries handle this more robustly.
Key Takeaways
- A module is simply any .py file, and it can be imported and reused elsewhere.
- import module, from module import name, and import module as alias are the three main import styles.
- The if __name__ == "__main__": idiom lets a file act as both a reusable module and a runnable script.
- Python's standard library ships with many useful built-in modules like math, random, and datetime.
- Python locates modules by searching the directories listed in sys.path, in order.
Summary
Modules are the basic unit of code reuse in Python — any .py file can be written once and imported wherever its functions or classes are needed. Understanding import, from...import, and import...as gives you full control over exactly what gets brought into your file.
You also saw why almost every real Python script uses the if __name__ == "__main__": idiom, and how Python's sys.path determines which modules can actually be found.
- You understand what a module is and how to create one.
- You can use all three import styles confidently.
- You understand the if __name__ == "__main__": idiom.
- You know how Python searches for modules using sys.path.