Modules and Packages · Lesson 25 of 39
Modules and Imports
As programs grow, one file is no longer enough. Python lets you split code into modules – ordinary .py files – and pull in what you need with import. The same mechanism gives you access to Python's huge standard library and to hundreds of thousands of third-party packages.
In this lesson
- The different ways to write an import
- Creating and using your own module
- What
if __name__ == "__main__":is for - Packages, and how Python finds what you import
Importing a module
import math
print(math.sqrt(81))
from math import pi, floor
print(floor(pi * 10))
import statistics as stats
print(stats.mean([4, 8, 9]))
9.0 31 7
| Style | Use it as | When |
|---|---|---|
import math | math.sqrt() | Default – clear where each name comes from |
from math import sqrt | sqrt() | You use a few names often |
import numpy as np | np.array() | Long names with a well-known short alias |
from math import * | everything | Avoid – names appear from nowhere and can clash |
Writing your own module
Any .py file is a module. Create pricing.py:
# pricing.py
GST_RATE = 0.18
def with_gst(amount):
return round(amount * (1 + GST_RATE), 2)
def discount(amount, percent):
return round(amount * (1 - percent / 100), 2)
Then use it from shop.py in the same folder:
# shop.py
import pricing
price = pricing.discount(1000, 10)
print(price, "→", pricing.with_gst(price))
900.0 → 1062.0
What import pricing does (first time only)
- Find pricing.pysearch the folders in sys.path
- Run the file oncetop-level code executes, names are created
- Cache the modulestored in sys.modules – later imports reuse it
- Bind the namepricing now refers to the module object
Common mistake: naming your file like a library
If you save your practice script as random.py, math.py or json.py, then import random loads your file instead of Python's, and you get baffling errors such as AttributeError: module 'random' has no attribute 'randint'. Rename the file (and delete any __pycache__ folder next to it).
if __name__ == "__main__"
Every module has a built-in variable __name__. When you run a file directly, it is "__main__"; when the file is imported, it is the module's name. This lets a file be both a reusable module and a runnable script:
# pricing.py
def with_gst(amount):
return round(amount * 1.18, 2)
if __name__ == "__main__":
# runs only with: python pricing.py
print("Self-test:", with_gst(100))
Self-test: 118.0
When shop.py imports pricing, the self-test does not run. Put demo code, quick tests and command-line entry points under this check.
Packages: folders of modules
A package is a folder that groups related modules. An __init__.py file marks it as a regular package and can hold setup code (it may be empty):
store/
├── main.py
└── billing/
├── __init__.py
├── pricing.py
└── invoice.py
# main.py
from billing import pricing
from billing.invoice import make_invoice
Inside a package, modules can import each other with relative imports: from .pricing import with_gst (the dot means "this package").
Where Python looks
sys.path is the list of folders searched, in order: the folder of the script you ran, then the standard library, then site-packages where pip installs packages.
import sys
import json
print(type(sys.path).__name__)
print("json" in sys.modules) # already loaded and cached
list True
Exploring a module
import random
print([name for name in dir(random) if name.startswith("rand")])
help_line = random.randint.__doc__.splitlines()[0]
print(help_line)
['randbytes', 'randint', 'random', 'randrange'] Return random integer in range [a, b], including both end points.
In the REPL, help(random.randint) shows the full documentation.
Practice
Try it yourself
Create
geometry.pywithcircle_area(r)andsquare_area(s), then import it from another file and print both areas for 3.Show solution
# geometry.py import math def circle_area(r): return math.pi * r ** 2 def square_area(s): return s * s# main.py from geometry import circle_area, square_area print(round(circle_area(3), 2), square_area(3))28.27 9
Use
from datetime import dateto print today's year.Show solution
from datetime import date print(date.today().year)
Quick check
What is __name__ when a file is run directly?
"__main__".
Does Python re-run a module's code every time you import it?
No. The first import runs it and caches it in sys.modules; later imports reuse the cached module.
Why avoid from module import *?
It dumps unknown names into your file, makes it unclear where they came from, and can silently overwrite your own names.
Summary
- A module is a
.pyfile; a package is a folder of modules. - Prefer
import moduleorfrom module import name; avoidimport *. if __name__ == "__main__":runs code only when the file is executed directly.- Don't name your files after standard modules.
Finished this lesson?
Mark it complete to track your progress, then carry on with the next lesson.