PythonWriting Your Own Module

Writing Your Own Module in Python

A module in Python is simply a .py file that contains Python code — variables, functions, classes, or any executable statements.

By writing your own modules, you can:

Organize your code Avoid repetition Improve readability Reuse code across multiple programs or projects


Why Write Your Own Modules?

BenefitDescription
Code ReuseShare common code across projects
Code OrganizationSplit large programs into logical components
Better MaintenanceEasier to debug and update
Promotes DRY principleDon’t Repeat Yourself

How to Create a Module

1️⃣ Create a .py file — this is your module. 2️⃣ Define variables, functions, or classes inside the file. 3️⃣ Import the module into other Python files.


Example 1: Create a Simple Module

File: mymath.py

mymath.py
# This is my custom module
 
def add(a, b):
    return a + b
 
def subtract(a, b):
    return a - b

Example 2: Import and Use Your Module

File: main.py

main.py
import mymath
 
print("Sum:", mymath.add(10, 5))
print("Difference:", mymath.subtract(10, 5))
output.txt
Sum: 15
Difference: 5

Example 3: Using from module import

main_import_specific.py
from mymath import add
 
print("Sum:", add(20, 10))
output.txt
Sum: 30

Where to Place Your Module

ScenarioModule Location
Same directory as your main scriptNo change needed
Different directoryAdd directory to sys.path
Shared project-wideInstall or link module using packaging tools

Example 4: Organizing with Packages

If you want to organize multiple modules:

myproject/

├── mypackage/
│   ├── __init__.py
│   ├── module1.py
│   ├── module2.py

└── main.py

In main.py:

main_package.py
from mypackage import module1
 
module1.some_function()

Example 5: Checking __name__

mymodule_with_name.py
def greet():
    print("Hello from my module!")
 
if __name__ == "__main__":
    greet()
output.txt
Hello from my module!

Explanation:

  • The __name__ variable allows a module to detect if it’s run as a script or imported as a module.

Summary

  • A module is simply a .py file.
  • Helps you split code into reusable parts.
  • Import your module using import module_name.
  • Use __init__.py to create packages of modules.
  • Organizing code into modules improves readability, testing, and maintainability.

In the next section, we will explore Installing Packages — how to bring in external modules from the wider Python ecosystem.


Would you like me to proceed with the next topic — Installing Packages — in the same style? Just confirm! 🚀