Python Modules & Packages
Jab program bada hota hai, saara code ek file me rakhna difficult ho jata hai. Modules aur packages code ko reusable, readable aur maintainable parts me organize karte hain.
What is a module?
A Python module is usually a .py file containing reusable variables, functions, classes or executable statements. Ek file ka useful code doosri file me import karke reuse kiya ja sakta hai.
import math
print(math.sqrt(81))
print(math.pi)math Python Standard Library ka module hai. import math ke baad module ka naam namespace ke roop me use hota hai, isliye math.sqrt() aur math.pi likhte hain.
Why use modules?
- Large program ko smaller files me divide karne ke liye.
- Same function ko multiple programs me reuse karne ke liye.
- Related code ko logically group karne ke liye.
- Testing and maintenance easier banane ke liye.
- Name collisions ko namespaces ke through reduce karne ke liye.
Common import styles
import math
from math import sqrt
import math as m
from math import pi as PI
print(math.factorial(5))
print(sqrt(49))
print(m.ceil(4.2))
print(PI)import module usually beginners ke liye clearest hota hai because source namespace visible rehta hai.
Avoid wildcard imports
# Avoid in normal application code:
# from math import *
from math import sqrt, floor
print(sqrt(64), floor(3.9))from module import * names ko current namespace me inject karta hai aur collisions/debugging difficult bana sakta hai. Explicit imports better hain.
Python Standard Library
Python ke saath bahut saare ready-made modules aate hain. Inhe separately install karne ki zaroorat nahi hoti.
import math
import random
from datetime import date
print(math.gcd(24, 36))
print(random.randint(1, 6))
print(date.today())random ki jagah secrets module use kiya jata hai.Create your own module
Suppose same folder me do files hain:
def add(a, b):
return a + b
def multiply(a, b):
return a * bimport calculator
print(calculator.add(10, 5))
print(calculator.multiply(4, 6))Jab main.py run hoti hai, Python calculator module locate karke uske definitions load karta hai.
Module namespace
Each module has its own namespace. Isi wajah se two modules same function name rakh sakte hain without immediate conflict.
import math
value = 25
print(math.sqrt(value))sqrt math namespace me hai; current file me direct sqrt name tab tak available nahi hoga jab tak explicitly import na karo.
__name__ and main guard
Python har module ko special __name__ value deta hai. Directly run ki gayi file me ye usually "__main__" hoti hai.
def show_report():
print("Report ready")
if __name__ == "__main__":
show_report()Main guard reusable definitions aur direct-run demo/testing code ko separate rakhne me useful hai.
Imports are cached during a process
Normal import ke baad module object sys.modules me cache hota hai. Same running process me repeated import usually module ka top-level code baar-baar execute nahi karta.
What is a package?
A package related modules ko directory structure me organize karta hai. Modern Python namespace packages bhi support karta hai, lekin beginner projects me __init__.py ke saath traditional package structure easiest to understand hota hai.
project/
├── main.py
└── utils/
├── __init__.py
├── text.py
└── numbers.pyImport from a package
from utils.text import clean_name
from utils.numbers import average
print(clean_name(" broun stack "))
print(average([80, 90, 70]))Dot notation package path ko represent karta hai: utils.text means utils package ke andar text module.
What does __init__.py do?
__init__.py traditional package ko explicit banata hai aur package import ke time initialization/export decisions ke liye use ho sakta hai. Beginner project me is file ko empty rakhna bhi perfectly fine hai.
from .text import clean_name
__all__ = ["clean_name"]Public API ko simplify karne ke liye package level par selected names expose kiye ja sakte hain, but unnecessary magic avoid karo.
Absolute vs relative imports
# Absolute import
from myapp.utils.text import clean_name
# Relative import (inside a package)
from .text import clean_name
from ..models import StudentAbsolute imports project structure ko explicit banate hain. Relative imports package ke andar useful ho sakte hain, but dots ka meaning beginners ko confusing lag sakta hai.
How Python finds modules
Import system module ko import path par search karta hai. Current execution context, installed packages aur configured paths is behavior ko affect karte hain.
import sys
for path in sys.path:
print(path)sys.path ko manually modify karna beginner projects me usually avoid karo. Better project structure aur proper package setup prefer karo.
Standard library vs third-party packages
math, json and datetime standard library ka part hain. Third-party libraries ko package manager se install karna padta hai.
python -m pip install package-namepip aur virtual environments ka detailed practical workflow Chapter 22 me cover hoga. Random package names blindly install mat karo; source, maintenance aur trust check karna important hai.
Module, package and distribution are not always the same
- Module: importable code unit, commonly a single
.pyfile. - Package: importable collection/namespace containing modules and subpackages.
- Distribution: installable project released through packaging tools/indexes; its install name and import name can differ.
Circular imports
When module A imports module B and B imports A during initialization, partially initialized modules and confusing errors aa sakte hain.
Do not shadow standard modules
Apni file ka naam random.py, json.py, math.py ya kisi imported library ke same naam par rakhne se import unexpected local file pick kar sakta hai.
Practical reusable module design
def average(marks):
if not marks:
return 0
return sum(marks) / len(marks)
def grade(score):
if score >= 90:
return "A"
if score >= 75:
return "B"
if score >= 60:
return "C"
return "D"from grade_tools import average, grade
marks = [82, 91, 76, 88]
score = average(marks)
print(f"Average: {score:.2f}")
print(f"Grade: {grade(score)}")Reusable module ko user input/printing se tightly couple karne ki jagah clear functions dena testing aur reuse easy banata hai.
What can you practice in BrounStack Playground?
Single-file Standard Library imports Playground me easily practice ho sakte hain. Multi-file custom module/package examples ko local editor/project environment me better test kiya jata hai because separate files required hote hain.
Run standard-library example →
Common beginner mistakes
- File ka naam imported standard module ke same rakhna.
from module import *overuse karna.- Wrong working directory/project structure ki wajah se
ModuleNotFoundErrorko code bug samajhna. - Installed distribution name aur import name ko always identical assume karna.
- Import time par heavy input/output ya side effects run karna.
__name__ == "__main__"pattern ko samjhe bina demo code import par execute kar dena.- Circular imports create karna.
- Relative imports ko ordinary standalone script me blindly use karna.
sys.pathhacks se broken project structure hide karna.- Unknown third-party package blindly install karna.
Beginner best practices
- Module names short, lowercase aur meaningful rakho.
- Related functions/classes ko ek focused module me group karo.
- Imports normally file ke top par organize karo.
- Standard library, third-party and local imports ko readable groups me rakho.
- Explicit imports prefer karo.
- Reusable modules me unnecessary global state avoid karo.
- Direct-run code ko main guard ke andar rakho when appropriate.
- Package structure ko simple rakho jab tak complexity genuinely required na ho.
Chapter checklist
- Module kya hota hai aur
importkaise work karta hai? import x,from x import yaur aliases ka difference clear hai?- Standard Library aur third-party package ka difference samajh aaya?
- Custom module ka basic two-file structure bana sakte ho?
__name__ == "__main__"ka use samajh aaya?- Package and
__init__.pyka role clear hai? - Absolute vs relative import ka basic difference pata hai?
- Circular imports aur module-name shadowing ke risks samajh aaye?
Practice Task — Student Toolkit Package
Local Python project me reusable student toolkit banao.
student_appproject folder banao.utilspackage banao with__init__.py.marks.pymodule meaverage()aurhighest()functions banao.grading.pymodule megrade()function banao.text.pymodule me student name clean/format function banao.main.pyme package functions import karo.- At least one
import modulestyle test karo. - At least one
from module import namestyle test karo. - One alias import use karo.
- One Standard Library module use karo.
if __name__ == "__main__":guard add karo.- Module file ko standard-library module name na do.
- One intentional wrong import karke error message observe karo, then fix karo.
- README-style note me project structure explain karo.