In Python, a module is a file containing Python definitions and statements. By creating custom modules, you can organize your code into reusable components. This article explains how to create and use custom modules with examples.
A Python module is a file with the extension .py
that contains Python code such as functions, classes, or variables. Modules help in structuring programs and promoting code reusability.
To create a custom module, write Python code in a file and save it with a .py
extension.
mymodule.py
# mymodule.py def greet(name): return f"Hello, {name}!" def add_numbers(a, b): return a + b PI = 3.14159
To use a custom module, import it in your Python script using the import
statement.
mymodule.py
# main.py # Import the custom module import mymodule # Call functions from the module print(mymodule.greet("Alice")) print("Sum:", mymodule.add_numbers(5, 10)) print("Value of PI:", mymodule.PI)
Save both mymodule.py
and main.py
in the same directory to ensure the module is accessible.
You can import specific functions or variables from a module using the from ... import
syntax.
# main.py from mymodule import greet, PI print(greet("Bob")) print("Value of PI:", PI)
You can assign an alias to a module or its components for convenience.
# main.py import mymodule as mm print(mm.greet("Charlie")) print("Sum:", mm.add_numbers(2, 3))
A package is a directory that contains multiple modules and a special file named __init__.py
.
Directory structure:
mypackage/ __init__.py math_operations.py string_operations.py
Content of math_operations.py
:
def multiply(a, b): return a * b
Content of string_operations.py
:
def to_uppercase(text): return text.upper()
Content of main.py
:
from mypackage.math_operations import multiply from mypackage.string_operations import to_uppercase print("Multiplication:", multiply(3, 4)) print("Uppercase:", to_uppercase("hello"))
Creating and using custom modules is an essential skill in Python. By structuring your code into reusable modules, you can improve code readability and maintainability while promoting collaboration and scalability.