📦 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:

ModulePurpose
mathMathematical operations
randomGenerate random numbers
datetimeWork with dates/time
osInteract with the system
sysAccess 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

ActionSyntax
Import moduleimport modulename
Import specific itemfrom modulename import item
Rename moduleimport modulename as alias
View module locationmodulename.__file__
See module documentationhelp(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