Python Module
A Python module is a .py file that contains Python code and can be imported into other Python scripts. This allows code to be reused across different programs and improves maintainability of a project.
Simple example of Python module
Suppose we have a file named math_ops.py
:
# math_ops.py
def add(a, b):
return a + b
def subtract(a, b):
return a - b
Now, we can use these functions in another Python script by importing the math_ops
module:
# main.py
import math_ops
print(math_ops.add(5, 3)) # Output: 8
print(math_ops.subtract(5, 3)) # Output: 2
Here, math_ops
is a module that we’ve created. It contains two functions, add
and subtract
. We can then import and use these functions in main.py
by using the module name and the function name, separated by a dot.