Python Imports: Modules, Packages, and from...import
Every nontrivial Python program spans more than one file. The import system is how those files find each other, and understanding it is what separates a script that runs on one machine from a package other people can install and reuse. This tutorial builds a tiny OrdersPortal package to show how modules, packages, aliases, and the import path fit together.
What you’ll learn
Section titled “What you’ll learn”- How the
importstatement andfrom...importbring names into a module. - How to alias imports and import from packages.
- How relative imports work inside a package.
- What the
if __name__ == "__main__":guard does and why every reusable script needs it. - How Python finds modules through
sys.pathand the common import patterns to use.
Prerequisites
Section titled “Prerequisites”- Python 3.9 or newer installed (run
python --versionto check). - A Python file you can run with
python filename.py. - Comfort with functions and basic types.
1. Import a whole module
Section titled “1. Import a whole module”A module is any .py file. import module runs the module and binds the module object to its name, so you access its contents with dot notation. This keeps the namespace explicit and avoids name clashes.
import math
radius = 5area = math.pi * radius ** 2print(round(area, 2)) # 78.54Verify: The script prints 78.54. Accessing pi without the math. prefix raises NameError.
2. Import specific names with from...import
Section titled “2. Import specific names with from...import”from module import name binds the name directly, so you drop the module prefix. Use it for names you use often, but keep the list short so the source of each name stays clear.
from math import sqrt, pi
print(round(sqrt(pi * 16), 4)) # 7.0898Verify: The script prints 7.0898.
3. Alias an import with as
Section titled “3. Alias an import with as”Rename an import with as. This is standard practice for libraries with long names or well-known conventions, and it resolves clashes when two modules define the same name.
import datetime as dtfrom ordersportal import calculate_total as total
print(dt.date(2026, 1, 15)) # 2026-01-15print(total([149.99, 49.99])) # 199.98 (depends on the imported function)Verify: The script prints a date and the order total. The alias only affects the name in your file, not the module itself.
4. Import from a package
Section titled “4. Import from a package”A package is a directory of modules. In Python 3.3+, a directory is a package even without __init__.py, but adding one is the clearest convention. Import a module from a package with dot notation.
Given this layout:
ordersportal/ __init__.py models.py pricing.pyfrom ordersportal.pricing import calculate_totalfrom ordersportal.models import Order
print(calculate_total([149.99, 49.99]))A package’s __init__.py can re-export names so users get a flatter API: from ordersportal.models import Order works directly as from ordersportal import Order when __init__.py contains from .models import Order.
Verify: Run the script from the directory that contains the ordersportal/ folder. It prints the total. If you see ModuleNotFoundError, run from the project root so the package is on the path.
5. Use relative imports inside a package
Section titled “5. Use relative imports inside a package”Inside a package, prefix the module with a dot for a relative import. One dot means the current package; two dots mean the parent package. Relative imports keep package-internal code independent of the package’s install name.
from .models import Order # .models = ordersportal.models
def calculate_total(lines: list[float]) -> float: return round(sum(lines), 2)Verify: Importing ordersportal.pricing works whether the package is named ordersportal or renamed on install. Relative imports only work inside a package, not in top-level scripts.
6. Guard the script entry point
Section titled “6. Guard the script entry point”Every module has a __name__ attribute. When you run a file directly, __name__ is "__main__"; when the file is imported, __name__ is the module’s name. Guarding the run-only code with if __name__ == "__main__": lets the file be imported for its functions without triggering side effects.
def print_report(orders: list[dict]) -> None: for o in orders: print(f"{o['id']}: {o['total']}")
if __name__ == "__main__": # runs only when executed directly, not when imported print_report([{"id": "ORD-001", "total": 149.99}])Verify: Running python reporting.py prints the report. Importing the module with from ordersportal import reporting does not print anything.
7. Understand how Python finds modules
Section titled “7. Understand how Python finds modules”When you import x, Python searches sys.path, an ordered list of directories. It starts with the script’s directory, then PYTHONPATH, then the standard library and installed packages. Knowing this explains ModuleNotFoundError and why you should run scripts from the project root.
import sys
for entry in sys.path: print(entry)Verify: The script prints each directory Python searches. The first entry is the directory of the running script.
Complete working example
Section titled “Complete working example”This example uses a small package and a script that imports it. Create the files below, then run python main.py from the project root.
from .pricing import calculate_total
__all__ = ["calculate_total"]from .models import Order # relative import inside the package
def calculate_total(lines: list[float]) -> float: """Return the sum of order line amounts, rounded to 2 decimals.""" return round(sum(lines), 2)from dataclasses import dataclass
@dataclassclass Order: id: str lines: list[float]from ordersportal import calculate_totalfrom ordersportal.models import Order
if __name__ == "__main__": order = Order(id="ORD-001", lines=[149.99, 49.99, 19.99]) print(f"{order.id} total: {calculate_total(order.lines):.2f}")Expected output:
ORD-001 total: 219.97Common mistakes
Section titled “Common mistakes”- Running from the wrong directory. A package import fails with
ModuleNotFoundErrorwhen the package folder is not onsys.path. Run scripts from the project root. - Using relative imports in a top-level script.
from .models import Orderinmain.pyraisesImportError. Relative imports only work inside a package. - Circular imports. Two modules importing each other at the top level can deadlock the import machinery. Move the import inside a function, or restructure so the dependency points one way.
from module import *. This dumps every public name into your namespace with no record of where each came from, and it ignores names unless__all__is set. Import names explicitly instead.- Forgetting the
__name__guard. Without it, importing your file runs all the top-level code, so tests and other modules trigger side effects they did not ask for.
Next steps
Section titled “Next steps”- Modules and packages course page — virtual environments,
pip, and distributing packages. - Scope — how names resolve across modules and functions.
- Type hints — annotating imported functions and classes.
Related pages
Section titled “Related pages”- Python basics index — overview of every basics page in one place.
- Functions basics — the functions you write inside the modules you import.
- Decorators intro — decorators rely on importing and reusing functions.
Official references
Section titled “Official references”- docs.python.org: Modules — the tutorial chapter on modules and packages.
- docs.python.org: The import system — how imports resolve, packages, and relative imports.
- docs.python.org: The import statement — the grammar and semantics of
importandfrom...import. - docs.python.org:
sys.path— the module search path.