agyanadda@gmail.com

Python Modules and Packages

Functions and Modules 1 min read Updated Dec 4, 2026 Topic 19 of 32

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

Example — A module and its use Python
# 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.

Test Yourself With Exercises

Exercise 1 Multiple Choice

Which import lets you call sqrt() directly?

Exercise 2 True / False

Code under if __name__ == "__main__": runs when the module is imported.

Exercise 3 Fill in the Blank

Give a module a short name: import numpy ___ np

Frequently Asked Questions

Either the package is not installed in the Python you are using (run pip install in the same virtual environment), the file name is misspelled, or your script is in a different folder from the module.