๐ฆ 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
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 transactionsvalidators.pyโ check amounts, currenciesreports.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.
Now split into modules:
Now the main script is clean โ it just orchestrates the modules:
๐ฏ Import styles in action
Here's how each import style works with the standard library (datetime, json, math, os, random):
โ๏ธ Writing your own module
Let's create the validators.py module that the main script imports:
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:
๐ Also used in
Where modules matter
import pandas as pd, from sklearn.model_selection import train_test_split.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.
๐ฏ Mini Challenge
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.
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.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.__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."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
import datetime do?if __name__ == "__main__":?calculations.py, how do you import the function add_fees from it in another script?๐ Quick Cheatsheet
| Import Style | Syntax | Usage | Pros / Cons |
|---|---|---|---|
| Full module | import datetime | datetime.datetime.now() | Clear origin; slightly verbose |
| Specific name | from datetime import datetime | datetime.now() | Shorter; lose origin clarity |
| With alias | import numpy as np | np.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 logic | Essential for reusable modules |
โ ๏ธ Common Mistakes
from module import *from module import specific_function or import module.if __name__ == "__main__": blockimport json, use json.dumps() โ not dumps(). If you from json import dumps, use dumps() โ not json.dumps(). Match the import style to the usage.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
.pyfile โ write one for reusable functions - Import styles:
import x(clear),from x import y(short),import x as z(alias), neverfrom 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__.pyfile โ they organize modules hierarchically - Python finds modules via
sys.pathโ understand the search order for imports to work
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 โ