In this tutorial, we will learn how to create custom Python modules and import both custom and built-in modules using different methods.
Modular programming is the practice of dividing a complex programming task into smaller, manageable sub-tasks called modules. Each module focuses on a specific part of the problem, making it easier to manage, understand, and maintain the program.
• Simplification: Modules are easier to work with since they focus on specific tasks.
• Flexibility: Changes made to one module are less likely to affect other parts of the program.
• Reusability: Functions defined in one module can be reused in different parts of the program without duplication.
• Scope: Each module has its own namespace, preventing naming conflicts across the program.
A module in Python is a file that contains Python code, including functions, classes, and variables. By using modules, you can split your code into different files to improve organization.
You can define a module in Python in several ways:
1. A regular Python file (.py) containing code.
2. A module written in C or C++ and dynamically linked during runtime.
3. Built-in modules included with the Python interpreter.
Let's create a Python module named example_module.py with the following code:
# example_module.py
# Function to cube a number
def cube(number):
return number ** 3
To use functions from another module, we can import them using the import statement. For example, to import our custom module example_module:
# main.py
import example_module
# Call the cube function from example_module
result = example_module.cube(3)
print("The cube of 3 is:", result)
The cube of 3 is: 27
1. Basic Import: You can import an entire module and use its functions with the dot (.) operator:
import math
print(math.pi) # Output: 3.141592653589793
2. Renaming a Module: You can assign a different name to a module while importing it:
import math as m
print(m.pi) # Output: 3.141592653589793
3. Import Specific Functions: You can import only specific functions from a module:
from math import pi
print(pi) # Output: 3.141592653589793
4. Import All Functions: You can import all functions from a module using the * operator (not recommended unless necessary):
from math import *
print(sqrt(16)) # Output: 4.0
Python searches for modules in several locations when importing. You can check the search path using the sys module:
import sys
print(sys.path)
The dir() function lists all names defined in a module:
import math
print(dir(math)) # Lists all functions and variables in the math module
Variables inside modules can be part of different namespaces, and Python distinguishes between local and global variables.
number = 100 # Global variable
def add_number():
global number
number += 50
print("Before:", number)
add_number()
print("After:", number)
Before: 100
After: 150