Import module in Python
In Python, modules allow us to organize code into reusable files, making it easy to import and use functions, classes, and variables from other scripts. Importing a module in Python is similar to using #include in C/C++, providing access to pre-written code and built-in libraries. Python’s import statement is the most common way to bring in external functionality, but there are multiple ways to do it.
Table of Content
Importing a Module in Python
The most common way to use a module is by importing it with the import statement. This allows access to all the functions and variables defined in the module. Example:
import math
pie = math.pi
print("The value of pi is:", pie)
Output
The value of pi is: 3.141592653589793
Explanation:
- math module is imported using import math.
- We access the constant pi using math.pi and then the value is printed as part of a formatted string.
Importing Specific Functions
Instead of importing the entire module, we can import only the functions or variables we need using the from keyword. This makes the code cleaner and avoids unnecessary imports.
from math import pi
print(pi)
Output
3.141592653589793
Explanation:
- from math import pi imports only the pi constant, so we can use it directly without math. prefix.
- This reduces unnecessary module overhead when only specific functions or constants are needed.
Importing Built-in Modules
Python provides many built-in modules that can be imported directly without installation. These modules offer ready-to-use functions for various tasks, such as random number generation, math operations and file handling.
import random
# Generate a random number between 1 and 10
res = random.randint(1, 10)
print("Random Number:", res)
Output
Random Number: 9
Explanation:
- import random brings in Python's built-in random module.
- random.randint(1, 10) generates a random integer between 1 and 10.
Importing Modules with Aliases
To make code more readable and concise, we can assign an alias to a module using the as keyword. This is especially useful when working with long module names.
import math as m
# Use the alias to call a function
result = m.sqrt(25)
print("Square root of 25:", result)
Output
Square root of 25: 5.0
Explanation:
- import math as m imports the math module and assigns it the alias m.
- m.sqrt(25) calls the square root function using the alias.
Importing Everything from a Module (*)
Instead of importing specific functions, we can import all functions and variables from a module using the * symbol. This allows direct access to all module contents without prefixing them with the module name.
from math import *
print(pi) # Accessing the constant 'pi'
print(factorial(6)) # Using the factorial function
Output
3.141592653589793 720
Explanation:
- from math import * imports all functions and constants from the math module.
- pi and factorial(6) are accessed directly without using math. as a prefix.
- While convenient, this method is not recommended in larger programs as it can lead to conflicts with existing variables and functions.
Handling Import Errors in Python
When importing a module that doesn’t exist or isn't installed, Python raises an ImportError. To prevent this, we can handle such cases using try-except blocks.
try:
import mathematics # Incorrect module name
print(mathematics.pi)
except ImportError:
print("Module not found! Please check the module name or install it if necessary.")
Output
3.141592653589793 720
Explanation:
- try block attempts to import a module, if the module is missing or misspelled, Python raises an ImportError.
- The except block catches the error and displays a user-friendly message instead of crashing the program.