Creating Custom Modules in Python

Loading

A module in Python is a file containing functions, classes, and variables that can be used in other Python programs. Creating custom modules helps in code reuse, organization, and maintainability.


1. Why Use Custom Modules?

Code Reusability – Write once, use multiple times.
Better Code Organization – Split large programs into multiple files.
Easier Debugging – Isolate errors to specific modules.
Collaboration – Multiple developers can work on different modules.


2. Creating a Custom Module

A module is just a Python file (.py) containing functions, classes, and variables.

2.1 Creating mymodule.py

# mymodule.py

def greet(name):
"""Returns a greeting message."""
return f"Hello, {name}!"

def add(a, b):
"""Returns the sum of two numbers."""
return a + b

PI = 3.14159 # A constant variable

3. Importing a Custom Module

After creating mymodule.py, you can import and use it in another Python script.

3.1 Importing the Entire Module

import mymodule

print(mymodule.greet("Alice")) # Output: Hello, Alice!
print(mymodule.add(5, 3)) # Output: 8
print(mymodule.PI) # Output: 3.14159

Access functions using mymodule.function_name().

3.2 Importing Specific Functions

from mymodule import greet, add

print(greet("Bob")) # Output: Hello, Bob!
print(add(10, 20)) # Output: 30

No need to use mymodule. prefix.

3.3 Importing with an Alias

import mymodule as mm

print(mm.greet("Charlie")) # Output: Hello, Charlie!

mm is an alias for mymodule to shorten function calls.


4. Using if __name__ == "__main__"

This ensures that some parts of the module only run when the file is executed directly.

4.1 Modify mymodule.py

def greet(name):
return f"Hello, {name}!"

if __name__ == "__main__":
print(greet("Alice")) # This runs only if executed directly

4.2 Running mymodule.py Directly

$ python mymodule.py
Hello, Alice!

4.3 Importing mymodule.py into Another Script

import mymodule
print(mymodule.greet("Bob"))

Only "Hello, Bob!" is printed because the if __name__ == "__main__": block is ignored when imported.


5. Storing Modules in a Package

A package is a directory containing multiple modules and a special __init__.py file.

5.1 Create a Folder (mypackage)

mypackage/
│── __init__.py # Required to treat it as a package
│── math_utils.py
│── string_utils.py

5.2 math_utils.py

def add(a, b):
return a + b

5.3 string_utils.py

def greet(name):
return f"Hello, {name}!"

5.4 Importing from the Package

from mypackage import math_utils, string_utils

print(math_utils.add(10, 5)) # Output: 15
print(string_utils.greet("Eva")) # Output: Hello, Eva!

Packages allow better structuring of multiple modules.


6. Reloading a Module (importlib)

If you modify a module, you may need to reload it without restarting Python.

import mymodule
import importlib

importlib.reload(mymodule)

7. Finding Module Location

Use the __file__ attribute to find where a module is stored.

import mymodule
print(mymodule.__file__) # Output: /path/to/mymodule.py

8. Summary

FeatureDescription
Creating a moduleSave Python functions in a .py file
Importing a moduleUse import module_name
Importing specific functionsUse from module import function
Using an aliasUse import module as alias
Checking if script is mainUse if __name__ == "__main__"
Creating a packageUse a folder with __init__.py

Leave a Reply

Your email address will not be published. Required fields are marked *