📃 Python Modules
Last Updated: 17th August 2025
- A module is a
.pyfile that contains functions, variables, or classes you can reuse. - Think of it like a toolbox: import it and use the tools inside.
Hinglish Tip 🗣: Module ko toolbox samjho. Ek baar tools bana liye, baar-baar use kar sakte ho—sirf
importkaro.
Module Types
There are Three Types of Modules:
- User-Defined Modules: Created by you.
- Built-in Modules: Part of the Python Standard Library.
- Third-Party Modules: External libraries.
User-Defined Modules
It help you organize your code into modules.
Folder layout (same directory):
project/
├─ myutils.py
└─ main.py
In myutils.py, we can write any functions, variables, or classes that we want to use in main.py.
# myutils.py
PI = 3.14159
def add(a, b):
return a + b
def square(x):
return x * x
# run-only-when-this-file-is-executed-directly
if __name__ == "__main__":
print("Quick self-test:", add(2, 3), square(4))
Hinglish Tip 🗣: name == "main" ka matlab: yeh code sirf tab chalega jab file direct run ho—import hone par nahi.
In main.py:
# main.py
# 1) Import full module
import myutils # import your module
print(myutils.add(10, 5)) # 15
print(myutils.square(6)) # 36
# 2) Import specific names
from myutils import add, square
print(add(10, 5)) # 15
print(square(6)) # 36
# 3) Import all names
from myutils import *
print(add(10, 5)) # 15
print(square(6)) # 36
print(PI) # 3.14159
# 4) Import with alias (short name)
import myutils as utils
print(utils.add(10, 5)) # 15
print(utils.square(6)) # 36
# 5) Import with alias (short name) and specific names
from myutils import add as a, square as s
print(a(10, 5)) # 15
print(s(6)) # 36
Built-in Modules
It is part of the Python Standard Library, and you can use it without installing any additional packages.Some of them are: math, random, datetime,time,os,re,csv etc.
Third-Party Modules
Third-party modules are packages that are not part of the Python Standard Library. You can install them using the pip package manager.e.g. numpy, pandas, matplotlib etc.
Hinglish Tip 🗣:
pipka matlab: Python ka koi bhi library install karo, tohpipka use karo.
💡 Quick Practice
- Create a module calc.py with functions: add(a,b), mean(lst) (no external libs). Import in another file and test.
- Make stringtools.py with to_snake(name: str) -> str and show usage from main.py.