π¦ Python Modules β Reuse Code Like a Pro | TechTown.in
As your Python projects grow bigger, youβll want to organize and reuse your code across different files. Thatβs where modules come in.
A module in Python is simply a file containing Python code β variables, functions, classes β that you can import and reuse anywhere.
In this guide, youβll learn how to create, use, and manage Python modules to build clean, efficient, and scalable code.
π§ What is a Module in Python?
A module is a .py file that contains reusable code.
You can use built-in modules like math, or create your own.
# math is a built-in module
import math
print(math.sqrt(16)) # Output: 4.0
β Modules keep your code organized, reusable, and easy to maintain.
π οΈ Create Your Own Module
Letβs say you make a file called mytools.py:
# mytools.py
def greet(name):
return f"Hello, {name}!"
Now, use this module in another file:
# main.py
import mytools
print(mytools.greet("Tanmay"))
π― Output:
Hello, Tanmay!
π Using import vs from Import
Basic import:
import mytools
mytools.greet("Aman")
Import specific item:
from mytools import greet
greet("Aman")
Import and rename:
import mytools as mt
mt.greet("Aman")
π Built-in Python Modules
Python comes with hundreds of standard modules:
| Module | Purpose |
|---|---|
math | Mathematical operations |
random | Generate random numbers |
datetime | Work with dates/time |
os | Interact with the system |
sys | Access system-specific info |
import random
print(random.randint(1, 100)) # Random number between 1 and 100
π Organizing Code with Packages
A package is a folder containing multiple modules + an __init__.py file.
myproject/
β
βββ mathutils/
β βββ __init__.py
β βββ calc.py
β βββ stats.py
You can import modules from a package:
from mathutils import calc
π Module Variables and Docstrings
# info.py
creator = "TechTown"
version = "1.0"
def about():
"""Returns info about this module"""
return f"{creator} v{version}"
import info
print(info.about())
β
Use __doc__ to see module descriptions.
π§ͺ Real-World Use Case: Utility Toolkit
Letβs say you’re building a student portal. Instead of repeating functions like calculate_grade(), send_email(), or log_activity() in every file, group them in a single module like utils.py.
Then you can reuse them everywhere with a single import.
π Summary β Python Modules Cheat Sheet
| Action | Syntax |
|---|---|
| Import module | import modulename |
| Import specific item | from modulename import item |
| Rename module | import modulename as alias |
| View module location | modulename.__file__ |
| See module documentation | help(modulename) |
π Final Thoughts
Python modules are the foundation of clean and maintainable code. Whether youβre importing built-in libraries or writing your own, modules help you break your project into manageable, reusable pieces.
Mastering modules will prepare you to build large-scale applications, APIs, data pipelines, and more.
π Learn more Python tricks and tools at TechTown.in