SyntaxPilot
Courses/Python/Lesson 19

Python · Lesson 19 of 40 · 13 min

Modules, packages and a standard library tour

queued

These are the notes for Python episode 19. Until now every program lived in a single file. Real projects have hundreds of files that share code. In this episode a chai shop's two apps carry copy-pasted copies of the same function, the copies drift apart, and we invent modules: write the code once, in one file, and import it everywhere. You will learn what a module is, the three safe ways to import (and why from module import * is a trap), the special variable __name__ and the if __name__ == "__main__": guard, packages (folders of modules), and a tour of the standard library: math, random, datetime, collections and statistics. Every single-file example below runs as-is in the SyntaxPilot compiler, with its real output from Python 3.13. The two-file examples (your own modules) need two files in one folder, so run those on your own computer; their outputs were also checked with Python 3.13.

The problem: two apps, one recipe, two prices

A chai shop has a billing app at the counter. It has a function bill() that adds a packing charge to an order. Later the shop builds a delivery app, which needs exactly the same calculation, so somebody copies the function and pastes it in. Quick and easy.

Months later the packing charge goes up from ₹5 to ₹10. The developer updates the billing app, and forgets the pasted copy.

billing.py:

def bill(amount):
    packing = 10   # updated!
    return amount + packing

print("Billing app:", bill(200))

Output:

Billing app: 210

delivery.py:

def bill(amount):
    packing = 5    # old copy
    return amount + packing

print("Delivery app:", bill(200))

Output:

Delivery app: 205

The same order costs ₹210 at the counter and ₹205 on delivery. No error, no warning: just two different answers. That's the worst kind of bug, because nothing tells you it's there.

Why it failed: one idea, many copies. Every change has to be made in every copy, and nobody remembers them all. With ten apps you'd have ten copies to hunt for.

The fix: write the function once, in one file, and let every program borrow it from there. Like a kitchen with one recipe book on the shelf, instead of every cook keeping a handwritten copy.

Your own module

In a kitchen In Python
The recipe book, written once, on the shelf shop.py: a module, one .py file
"Bring me the recipe book" import shop: load that file
Follow the masala chai recipe on page 12 shop.bill(200): module.name
Fix the book once, every cook gets the fix edit shop.py, every importer is updated

A module is just a normal Python file (.py) that holds functions and values. Any other Python file in the same folder can import it.

shop.py:

# shop.py: written ONCE
def bill(amount):
    packing = 10
    return amount + packing

GST = 0.05

main.py (in the same folder):

# main.py (same folder)
import shop

print(shop.bill(200))
print(shop.GST)

Run python main.py. Output:

210
0.05

How it works:

  1. import shop makes Python look for a file called shop.py (first in your program's folder, then in Python's own library folders).
  2. Python runs that file once, top to bottom, and keeps everything it defined in a module object called shop.
  3. You use what's inside with a dot: shop.bill, shop.GST. The module name works like a surname: shop.bill is "the bill that belongs to shop".

Now both the billing app and the delivery app import shop. Change the packing charge in one place and both are right. You just invented modules.

Notes:

  • You write import shop, not import shop.py.
  • The file name must be a valid Python name: shop_utils.py is fine, shop-utils.py or 2shop.py can't be imported.
  • A module is loaded once per program run. Importing it again in another file reuses the same module object.
  • The online compiler runs a single file, so try your own modules on your computer with two files in one folder. Everything else in these notes runs in the compiler, because Python ships with hundreds of ready-made modules.

Three ways to import

1. import math

The first ready-made module: math.

import math

print(math.sqrt(144))
print(math.ceil(50 / 6))   # boxes of 6
print(math.pi)

Output:

12.0
9
3.141592653589793

math.sqrt is the square root. math.ceil rounds up: 50 samosas in boxes of 6 need 9 boxes, because 8 boxes hold only 48. Every name is written as math.something, so you always know where it came from.

The star import trap

Typing math. every time feels long, so people find a shortcut: from math import *. The star means "bring every name in the module straight into my file". Watch carefully. The first line uses Python's built-in pow, which can take three numbers: pow(2, 3, 5) is 2 to the power 3, remainder after dividing by 5 (8 % 5 = 3).

print(pow(2, 3, 5))     # built-in pow

from math import *
print(sqrt(144))
print(pow(2, 3, 5))

Output:

3
12.0
Traceback (most recent call last):
  File "main.py", line 5, in <module>
    print(pow(2, 3, 5))
          ~~~^^^^^^^^^
TypeError: pow expected 2 arguments, got 3

The same line worked a moment ago. Why: the math module has its own pow, which takes only two numbers. The star import quietly replaced Python's built-in pow with math.pow. You never saw it happen, because the star brings in names you never asked for (the math module has over 60 of them). The same thing can happen between two of your own modules: if both define total, the later star import silently wins.

2. from math import sqrt, ceil and 3. import statistics as st

The three safe ways:

Style How you use it When
import math math.sqrt(81) the default: clearest, nothing gets replaced
from math import sqrt, ceil sqrt(81) only the names you list come in
import statistics as st st.mean(...) as gives the module a short nickname (an alias)
from math import * sqrt(81) avoid: brings in everything, can overwrite names
import math
from math import sqrt
import statistics as st

print(math.floor(7.9))
print(sqrt(81))
print(st.mean([120, 340, 90, 450]))
print(pow(2, 3, 5))     # still the built-in

Output:

7
9.0
250
3

math.floor rounds down. sqrt came in by name, so no prefix is needed. st.mean is the average. And pow still works, because nothing replaced it. You'll see as everywhere in real code: import pandas as pd, import numpy as np.

You can also rename a single name: from math import sqrt as root. And you can import several modules on one line, import random, statistics, math, though one per line is easier to read.

__name__ and if __name__ == "__main__":

The problem: the recipe book that cooks by itself

While writing shop.py, you add a quick test at the bottom. Run shop.py and it prints TEST: 110. Good. But import doesn't just read a file: it runs the whole file, top to bottom, once. So every app that imports shop also prints your test line.

shop.py:

# shop.py
def bill(amount):
    return amount + 10

# quick test
print("TEST:", bill(100))

main.py:

# main.py
import shop

print("Order:", shop.bill(250))

Run python main.py. Output:

TEST: 110
Order: 260

The test leaked into the app. The file needs a way to ask: "am I being run directly, or am I being imported?"

__name__

Every file has a hidden variable called __name__ (two underscores on each side; people say "dunder name", short for double underscore).

print("I am running as:", __name__)

Output:

I am running as: __main__
  • When you run a file directly, Python sets its __name__ to the string "__main__".
  • When the same file is imported, its __name__ is the module's name instead: "shop".

The main guard

# shop.py
def bill(amount):
    return amount + 10

if __name__ == "__main__":
    print("TEST:", bill(100))

Run python shop.py directly:

TEST: 110

Run python main.py (which imports shop):

Order: 260

When imported, __name__ is "shop", the condition is False, and the test is skipped. That's the famous main guard: code under it runs only when the file is the program, never when it's borrowed. You'll see it at the bottom of almost every Python file, often as:

def main():
    ...

if __name__ == "__main__":
    main()

Packages: folders of modules

As the shop grows, one module isn't enough: billing, stock, delivery. Twenty files loose in one folder gets messy, so you do what you do with papers: put related files in a folder. A folder of modules is called a package.

my_project/
├── main.py
└── shop/              ← the package (a folder)
    ├── __init__.py    ← marks the folder as a package (can be empty)
    ├── billing.py     ← def bill(amount)
    ├── stock.py       ← def restock(item, qty)
    └── delivery.py    ← def fee(km)

__init__.py ("dunder init dot py") can be completely empty. It tells Python and the reader "this folder is a package", and any code in it runs when the package is first imported. (Modern Python can import a folder without it, as a "namespace package", but adding __init__.py is the normal, clear way.)

You reach inside with dots, like a file path:

shop/billing.py:

def bill(amount):
    return amount + 10

shop/stock.py:

def restock(item, qty):
    return f"Order {qty} more {item}"

main.py:

from shop.billing import bill
import shop.stock as stock

print(bill(200))
print(stock.restock("milk", 5))

Output:

210
Order 5 more milk

Packages can contain packages (shop/reports/daily.py → import shop.reports.daily).

Where modules come from

Kind Examples How you get it
Your own shop.py, greet.py write it in your project folder
The standard library math, random, datetime, collections, statistics, json, csv, os comes free with every Python install: just import
Third-party requests, pandas, numpy, flask install with pip (pip install requests), episode 30

Rule of thumb: before you write a tool yourself, check whether Python already ships it.

Standard library tour

random: a lucky draw

import random

friends = ["Asha", "Ravi", "Meena", "Arjun"]
random.seed(7)   # same result every run
print("Lucky draw:", random.choice(friends))
print("Dice:", random.randint(1, 6))

Output:

Lucky draw: Meena
Dice: 2
  • random.choice(list) picks one item.
  • random.randint(a, b) gives a whole number from a to b, both included.
  • random.shuffle(list) mixes a list in place; random.random() gives a float from 0 to 1.
  • random.seed(n) makes the "random" results the same on every run: handy for testing and for these notes. Remove the seed and you get different answers each time.

datetime: days to Diwali

from datetime import date

today = date(2026, 10, 30)
diwali = date(2026, 11, 8)
print("Days to Diwali:", (diwali - today).days)
print(diwali.strftime("%d %B %Y"))

Output:

Days to Diwali: 9
08 November 2026

Subtracting two dates gives a timedelta (a length of time); .days is its number of days. strftime ("string format time") turns a date into text: %d day, %B full month name, %b short month name, %Y year. The module knows the calendar, months of different lengths and leap years included. Use date.today() for the real current date.

collections.Counter: the best seller

from collections import Counter

orders = ["chai", "samosa", "chai", "vada pav", "chai", "samosa"]
count = Counter(orders)
print(count)
print(count.most_common(1))

Output:

Counter({'chai': 3, 'samosa': 2, 'vada pav': 1})
[('chai', 3)]

Counter is a dictionary that counts things. It does in one line what the counting loop with a dictionary did in episode 12. most_common(n) gives the top n as (item, count) pairs.

Cheat sheet

Module Useful for Try
math maths sqrt, ceil, floor, pi, gcd
random random choices choice, randint, shuffle, seed
datetime dates and times date, datetime, timedelta, strftime
collections smarter containers Counter, defaultdict, deque
statistics averages mean, median, mode
os, pathlib files and folders os.listdir, Path("a.txt").exists()
json, csv data files episode 20
time pausing, timing code time.sleep(1), time.time()

To explore a module: help(math) shows its documentation, dir(math) lists every name inside it, and the official Python docs have a "Library Reference" with every standard module.

Common mistakes

Naming your file after a module

You're practising random, so you name your file random.py:

# file name: random.py  (oops!)
import random

print(random.choice(["Asha", "Ravi"]))

Running it on your computer:

AttributeError: module 'random' has no attribute 'choice' (consider renaming '/home/you/random.py' since it has the same name as the standard library module named 'random' and prevents importing that standard library module)

Of course random has choice! But Python looks in your program's folder first. It found your own random.py and imported that instead (this is called shadowing). Newer Python versions add the hint in brackets. The fix: never name your files after modules you use (random.py, math.py, json.py, csv.py...). Call it lucky_draw.py, and delete any leftover __pycache__ folder.

All of today's mistakes

Mistake Exact error Why Fix
import maths ModuleNotFoundError: No module named 'maths' a typo, or a third-party module that isn't installed import math (or pip install ...)
math.squareroot(16) AttributeError: module 'math' has no attribute 'squareroot' no such name in the module math.sqrt(16); check with dir(math)
from math import * then pow(2, 3, 5) TypeError: pow expected 2 arguments, got 3 the star import replaced the built-in pow import math
a file named random.py AttributeError: module 'random' has no attribute 'choice' your file shadows the real module rename your file
test prints at the bottom of shop.py No error: the tests print in every app import runs the whole file if __name__ == "__main__":
pasted copies of a function No error: two apps give different answers the copies drift apart one module, imported everywhere

Mini project: a chai shop day report

An end-of-day report built only from the standard library:

  • datetime: the date, nicely printed
  • Counter: the best seller
  • statistics: the average bill
  • math.ceil: cups to order for tomorrow (1.5 × today's orders, rounded up)
  • random: a lucky customer who gets free tea
# Mini project: chai shop day report
import random, statistics, math
from collections import Counter
from datetime import date

orders = ["chai", "samosa", "chai", "bun", "chai", "samosa"]
bills = [120, 340, 90, 450, 75]

print("Report for", date(2026, 10, 30).strftime("%d %b %Y"))
print("Best seller:", Counter(orders).most_common(1)[0][0])
print("Average bill:", statistics.mean(bills))
print("Cups to order:", math.ceil(len(orders) * 1.5))
random.seed(19)
print("Lucky customer: bill no.", random.randint(1, len(bills)))

Output:

Report for 30 Oct 2026
Best seller: chai
Average bill: 215
Cups to order: 9
Lucky customer: bill no. 1

Imports go at the top of a file, so a reader sees at once what the file depends on. most_common(1) gives [('chai', 3)]; [0][0] takes the first pair, then its first item.

Extend it: add the median bill with statistics.median(bills) (it's 120), and replace the fixed date with date.today().

Practice

1. Make greet.py with a function hello(name), and import it from main.py. 2. Add a main guard with a test to greet.py.

Solution

greet.py:

def hello(name):
    return f"Hello, {name}! Welcome to the chai shop."

if __name__ == "__main__":
    print("TEST:", hello("Asha"))

main.py (same folder):

import greet

print(greet.hello("Ravi"))

python main.py prints:

Hello, Ravi! Welcome to the chai shop.

python greet.py prints:

TEST: Hello, Asha! Welcome to the chai shop.

3. Roll two dice 5 times with random and print each total.

Solution
import random

random.seed(3)
for i in range(1, 6):
    a = random.randint(1, 6)
    b = random.randint(1, 6)
    print("Roll", i, ":", a, "+", b, "=", a + b)

Output (with seed 3):

Roll 1 : 2 + 5 = 7
Roll 2 : 5 + 2 = 7
Roll 3 : 3 + 5 = 8
Roll 4 : 4 + 6 = 10
Roll 5 : 5 + 1 = 6

4. Days left until your next birthday, with datetime.

Solution
from datetime import date

today = date(2026, 10, 30)
birthday = date(2027, 3, 14)
print("Days to go:", (birthday - today).days)

Output:

Days to go: 135

Use date.today() instead of the fixed date to get the real answer.

5. Find the two most common letters in "mississippi".

Solution
from collections import Counter

print(Counter("mississippi").most_common(2))

Output:

[('i', 4), ('s', 4)]

A string is a sequence of characters, so Counter counts each letter.

Quick quiz

1. The video's quiz. We run main.py. What does it print?

# helper.py
print("A")
if __name__ == "__main__":
    print("B")

# main.py
import helper
print("C")
Answer
A
C

Importing runs helper.py top to bottom, so A prints. Its __name__ is "helper", not "__main__", so B is skipped. Then main.py prints C.

2. After from math import *, what does pow(2, 3, 5) do?

Answer

It raises TypeError: pow expected 2 arguments, got 3, because the star import replaced the built-in pow with math.pow, which takes only two arguments.

3. What does import statistics as st do?

Answer

It imports the statistics module under the short name (alias) st, so you write st.mean(...). The name statistics itself is not defined in your file.

4. What makes a folder a package?

Answer

It's a folder of modules, normally with an __init__.py file inside (which can be empty). You import from it with dots: from shop.billing import bill.

Interview questions

  1. What is a module in Python? Any .py file; its functions, classes and variables can be used by other files through import.
  2. What is a package? A folder of modules (normally with an __init__.py), imported with dotted names like shop.billing.
  3. What does if __name__ == "__main__": do? It runs the code below it only when the file is executed directly, not when it's imported. __name__ is "__main__" for the running file and the module's name when imported.
  4. Difference between import math and from math import sqrt? The first binds the module name math (use math.sqrt); the second binds only sqrt directly in your namespace.
  5. Why is from module import * discouraged? It pulls in unknown names, can silently overwrite existing ones (like the built-in pow), and makes it unclear where a name came from.
  6. What happens when you import a module twice? It runs only once per program; later imports reuse the cached module object (stored in sys.modules).
  7. How does Python find a module? It searches the folder of the running script first, then the standard library and installed packages, in the order listed in sys.path. That's why a file named random.py shadows the real random.
  8. Standard library vs third-party packages? The standard library ships with Python; third-party packages are installed separately, usually with pip.
  9. What is __init__.py for? It marks a folder as a regular package and runs when the package is first imported; it can be empty or set up what the package exposes.

Glossary

Term Meaning Example
Module A Python file whose contents other files can import shop.py
import Loads a module (running it once) and gives you its name import math
from ... import ... Imports chosen names straight into your file from math import sqrt
Alias (as) A nickname for a module or name import statistics as st
Star import from x import *: brings in every name (avoid) from math import *
Namespace The set of names a file or module knows; math.pi lives in math's namespace math.pi vs your own pi
Dot notation module.name: a name that belongs to a module shop.bill(200)
Built-in A name Python always has, without importing print, len, pow
Shadowing A name or file hiding another with the same name random.py hides random
__name__ Each file's name: "__main__" when run directly, the module name when imported print(__name__)
Dunder "Double underscore": names like __name__, __init__ __main__
Main guard if __name__ == "__main__": code that runs only when executed directly tests at the bottom of a module
Package A folder of modules shop/
__init__.py The file that marks a folder as a package (can be empty) shop/__init__.py
Standard library The modules that come free with Python math, random, datetime
Third-party package A package written by others, installed separately requests, pandas
pip Python's tool for installing third-party packages (episode 30) pip install requests
ModuleNotFoundError Python can't find a module with that name import maths
AttributeError The module (or object) has no such name math.squareroot
math.ceil / math.floor Round up / round down to a whole number math.ceil(50 / 6) → 9
random.seed Makes random results repeatable random.seed(7)
randint(a, b) A random whole number from a to b, both included random.randint(1, 6)
timedelta A length of time; the result of subtracting dates (diwali - today).days
strftime Formats a date as text "%d %B %Y"
Counter A dict that counts items Counter(orders)
statistics.mean The average of numbers mean([120, 340])
dir() / help() List the names in a module / show its documentation dir(math)

Summary

  • Copy-pasted code drifts apart: fix one copy and the others stay wrong, silently.
  • A module is one .py file. Write code once and import it everywhere; use it as module.name.
  • Three safe imports: import math, from math import sqrt, import statistics as st. Avoid from math import *: it can silently overwrite names (the built-in pow).
  • import runs the file. Put test code under if __name__ == "__main__": so it runs only when the file is executed directly.
  • A package is a folder of modules with an __init__.py; import with dots: from shop.billing import bill.
  • The standard library already has most everyday tools: math, random, datetime, collections.Counter, statistics, and more. Third-party packages come with pip.
  • Never name your own file after a module you use (random.py).

Next episode: file handling. Everything our programs stored so far vanished the moment they ended. Next time you'll save data to files, CSV and JSON, so it's still there tomorrow.