Modules and packages
A module is a file of Python code you can import into another file. Splitting a program into modules keeps each file focused, and importing from the standard library or third party packages gives you thousands of ready made tools.
Importing a standard library module
import math
print(math.sqrt(49))
print(math.pi)import math loads the module and makes its contents available under the name math.
Importing specific names
from math import sqrt, pi
print(sqrt(49), pi)Now sqrt is available directly. Avoid from math import *; it dumps every name into your file and makes it unclear where things came from.
Aliases
import datetime as dt
print(dt.date.today().year)Aliases are conventional for some libraries: import numpy as np, import pandas as pd.
Writing your own module
Any .py file is a module. Suppose helpers.py contains:
# helpers.py
TAX_RATE = 0.18
def with_tax(amount):
return round(amount * (1 + TAX_RATE), 2)A file in the same folder can use it:
# main.py
import helpers
print(helpers.with_tax(100))
from helpers import with_tax
print(with_tax(250))if name == "main"
When a file is run directly, Python sets its __name__ to "__main__". When it is imported, __name__ is the module's name. This lets a file be both a script and an importable module.
def main():
print("Running as a script")
if __name__ == "__main__":
main()Test code and command line entry points go under this guard so they do not run on import.
Packages
A package is a folder of modules, usually with an __init__.py file. Dots separate the levels.
shop/
__init__.py
cart.py
payments.pyfrom shop.cart import add_item
import shop.payments as payWhere Python looks for modules
sys.path lists the folders searched in order: the script's folder, then the standard library, then installed packages.
import sys
print(sys.path[:3])Exploring a module
import math
print([name for name in dir(math) if not name.startswith("_")][:10])
help(math.gcd)Useful standard library modules
| Module | Purpose |
|---|---|
os, pathlib, shutil | Files and folders |
sys | Interpreter details, command line arguments |
datetime, time | Dates and timing |
math, statistics, random | Maths |
json, csv | Data formats |
re | Regular expressions |
collections, itertools, functools | Data structure and function helpers |
logging | Structured log output |
unittest | Testing |
urllib, http | Networking |
Practice
- Create
geometry.pywithcircle_area(r)andrect_area(w, h), then import and use both from another file. - Add a
__main__guard togeometry.pythat prints a demo when run directly, and check it does not print when imported. - Use
dir()on therandommodule and try three functions you have not used before.
