A module is a .py file. A package is a folder of modules (usually with an __init__.py file).
Import styles
import math→math.sqrt(16)from math import sqrt, pi→sqrt(16)import datetime as dt— an alias- Avoid
from module import *— it hides where names come from
The standard library
Python ships with hundreds of modules: os, sys, pathlib, math, random, datetime, json, csv, re, collections, itertools, statistics, urllib, sqlite3, logging.
Your own module
Save functions in utils.py, then import utils from a file in the same folder.
if __name__ == "__main__":
Code under this check runs only when the file is run directly, not when it is imported. Put test or start-up code there.
Packages
shop/
__init__.py
cart.py
payments.py
from shop.cart import add_item
Third-party packages are installed with pip (next lesson).
Example
# utils.py
def rupees(amount: float) -> str:
return f"₹{amount:,.2f}"
def gst(amount: float, rate: float = 18) -> float:
return round(amount * rate / 100, 2)
if __name__ == "__main__":
# runs only with: python utils.py
print("Testing:", rupees(1234.5), gst(1000))
# main.py
import statistics
from datetime import date
from utils import rupees, gst
sales = [1200, 3400, 2800, 4100]
print("Date:", date.today())
print("Average sale:", rupees(statistics.mean(sales)))
print("GST on 2800:", rupees(gst(2800)))
python main.py prints today's date, Average sale: ₹2,875.00 and GST on 2800: ₹504.00. The test line in utils.py does not run when it is imported.