๐Ÿ“ฆ What is a module?

A module is any .py file. That's it. Every Python file you've written is a module. When you break a long script into separate files โ€” one for logic, one for validation, one for output โ€” you're creating modules.

The power of modules is code reuse. Instead of copying the same validation function into every script, write it once in validators.py, then import it wherever you need it. Python's standard library โ€” datetime, json, csv, os, random, math โ€” are all modules too.

Core idea: A module is a reusable collection of functions, classes, and variables in a single .py file. Import it with import module_name to use its code elsewhere.

๐Ÿ”— Four ways to import

Python offers several import syntax options, each suited to different scenarios.

1. Import the entire module

import datetime loads the whole module. You access functions via dot notation: datetime.datetime.now(). This is clear โ€” you always know where the function came from.

2. Import specific names

from datetime import datetime imports just the datetime class. Now you call it directly: datetime.now(). Shorter, but less explicit about where it came from.

3. Import with an alias

import json as j renames the module to a shorter name. Useful for long names like matplotlib.pyplot which becomes import matplotlib.pyplot as plt. This is the most popular pattern in data science.

4. Import everything (avoid this)

from module import * imports all public names. This pollutes your namespace โ€” you won't know where a function came from, and it can cause naming conflicts. Professional code avoids it.

Import styles: Use import x for clarity, from x import y when you use one function often, import x as z for readability. Never use from x import *.

๐Ÿฆ Business scenario

๐Ÿฆ
Scenario
SouthBank India โ€” Daily Reconciliation

SouthBank India processes thousands of transactions daily. Every night, they run a reconciliation script: validate transaction amounts, calculate fees, generate a report. The script is 200+ lines โ€” hard to test, hard to share with other teams.

Solution: Split it into three modules:

  • transactions.py โ€” read and store transactions
  • validators.py โ€” check amounts, currencies
  • reports.py โ€” format and output results

Now the main script is 30 lines. Each module is testable in isolation. Teams can use validators without running the full reconciliation.

๐Ÿ’ป Code Example 1: Before and after

This is a monolithic 200-line script โ€” hard to test and reuse.

reconciliation_old.py (monolithic)Before refactor

Now split into modules:

transactions.py (new module)After refactor

Now the main script is clean โ€” it just orchestrates the modules:

reconciliation_new.py (main, imports others)Refactored main

๐ŸŽฏ Import styles in action

Here's how each import style works with the standard library (datetime, json, math, os, random):

import_examples.pyReal-world patterns

โœ๏ธ Writing your own module

Let's create the validators.py module that the main script imports:

validators.py (custom module)A reusable module

Notice the if __name__ == "__main__": block at the bottom. This is Python's idiom for "run this code only if the file is executed directly, not when imported."

๐ŸŽญ The if __name__ == "__main__": idiom

When you import a module, Python executes all its code โ€” but not the code inside the if __name__ == "__main__": block.

  • If you run the file directly: python validators.py, then __name__ is "__main__" โ€” the block runs.
  • If you import it: from validators import is_valid_txn, then __name__ is the module name "validators" โ€” the block is skipped.

This pattern lets you write test code inside a module without it running when the module is imported.

The idiom: Always wrap your main logic or tests in if __name__ == "__main__": at the module level. This makes the module both runnable and importable.

โญ Standard library highlights

Python ships with dozens of modules. Here are the essentials:

datetime
now(), timedelta
Work with dates, times, and durations
json
dumps(), loads()
Parse and create JSON strings
csv
reader(), writer()
Read and write CSV files
os
getcwd(), listdir()
File system and environment access
math
sqrt(), sin(), ceil()
Mathematical functions
random
randint(), choice()
Generate random numbers and samples

๐ŸŒ Also used in

Where modules matter

๐Ÿฆ
Banking: JSON โ†’ CSV reconciliation
Import json to parse transaction feeds, csv to output reports, datetime for timestamps.
๐Ÿ“Š
Data Science: pandas + NumPy + sklearn
Every ML pipeline imports specialized modules: import pandas as pd, from sklearn.model_selection import train_test_split.
๐ŸŒ
Web: Flask, Django, FastAPI
Modern web apps are just modular Python. from flask import Flask imports the web framework.

๐Ÿค– How does this connect to AI?

Every machine learning pipeline is a series of imported modules. A typical workflow looks like: from sklearn.datasets import load_iris (load data), from sklearn.model_selection import train_test_split (split), from sklearn.ensemble import RandomForestClassifier (train). Professional ML code is modular โ€” each step in its own module or function.

scikit-learn TensorFlow PyTorch pandas

๐ŸŽฏ Mini Challenge

Create a currency converter module

Create a file currency.py with a function convert(amount, from_code, to_code, rate) that returns the converted amount. It should validate that amounts are positive and codes are 3 characters. Then create a main script that imports it and uses it to convert โ‚น5000 INR to USD at a rate of 0.012. Run the converter twice with different inputs to test.

In currency.py, define the function with validation checks. At the bottom, use if __name__ == "__main__": to test the function. Then in your main script, use from currency import convert to import and call it twice.

๐ŸŽค Interview Questions

import x loads the entire module; you access its contents via x.function_name(). from x import y imports just the item y directly; you call it as y(). The first is more explicit about where things come from. The second is shorter but less clear.
It marks code that should run only when the file is executed directly, not when it's imported. When you python script.py, the block runs. When you from script import some_function, it doesn't. This lets every module be both reusable and runnable.
from module import * imports every public name from a module into your namespace without explicit labels. You lose track of where functions come from, and there's a risk of name collisions if the module has a function with the same name as one you already defined. Professional code avoids this pattern.
A package is a directory that contains Python modules and an __init__.py file. For example, if you have a folder mypackage/ with __init__.py, utils.py, and validators.py, then from mypackage.utils import some_function works. The __init__.py file (even if empty) tells Python "this is a package, not just a folder."
Python uses the module search path, which is a list of directories stored in sys.path. It searches in this order: (1) the directory of the script being run, (2) directories in the PYTHONPATH environment variable, (3) standard library directories, (4) site-packages (third-party packages). You can inspect it: import sys; print(sys.path). This is why installing with pip works โ€” pip puts packages into site-packages which is always in sys.path.

๐Ÿง  Quick Quiz

Question 1 of 5
What does import datetime do?
Question 2 of 5
What is the purpose of if __name__ == "__main__":?
Question 3 of 5
Which import style is considered a best practice?
Question 4 of 5
What is a Python module?
Question 5 of 5
If you have a file calculations.py, how do you import the function add_fees from it in another script?
0
/5

๐Ÿ“‹ Quick Cheatsheet

Import StyleSyntaxUsagePros / Cons
Full moduleimport datetimedatetime.datetime.now()Clear origin; slightly verbose
Specific namefrom datetime import datetimedatetime.now()Shorter; lose origin clarity
With aliasimport numpy as npnp.array()Readable for long names; convention-dependent
Star (avoid)from json import *dumps()Pollutes namespace; causes collisions
__name__if __name__ == "__main__":Test code or main logicEssential for reusable modules

โš ๏ธ Common Mistakes

Using from module import *
You lose track of where functions come from and risk naming collisions. Always be explicit: from module import specific_function or import module.
Forgetting the if __name__ == "__main__": block
If you don't wrap test code in this block, it runs when the module is imported โ€” causing unexpected side effects. Always wrap test and demo code.
Importing a module but using the wrong syntax
If you import json, use json.dumps() โ€” not dumps(). If you from json import dumps, use dumps() โ€” not json.dumps(). Match the import style to the usage.
Not understanding the module search path
If Python can't find a module, it's not in sys.path. Either move it to the same directory, add its directory to sys.path, or install it with pip. For custom modules, keep them in the same directory as your script during development.

โœฆ Key Takeaways

  • A module is any .py file โ€” write one for reusable functions
  • Import styles: import x (clear), from x import y (short), import x as z (alias), never from x import *
  • Always wrap test code in if __name__ == "__main__": to make modules both reusable and runnable
  • Standard library essentials: datetime, json, csv, os, math, random
  • Packages are directories with an __init__.py file โ€” they organize modules hierarchically
  • Python finds modules via sys.path โ€” understand the search order for imports to work
Africa & India's Best AI Academy
๐Ÿค– AI-first ๐ŸŽ“ Placement Assistance

You've mastered modules.
Now build real applications.

Join the Best AI Program: The AI-Era Analyst โ€” 5 months, fully online, with placement assistance. Week 1 is free.

Explore The AI-Era Analyst โ†’