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.
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:
Python
import math
pie = math.pi
print("The value of pi is:", pie)
OutputThe 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.
Python
from math import pi
print(pi)
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.
Python
import random
# Generate a random number between 1 and 10
res = random.randint(1, 10)
print("Random Number:", res)
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.
Python
import math as m
# Use the alias to call a function
result = m.sqrt(25)
print("Square root of 25:", result)
OutputSquare 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.
Python
from math import *
print(pi) # Accessing the constant 'pi'
print(factorial(6)) # Using the factorial function
Output3.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.
Python
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.")
Output3.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.
Similar Reads
Lazy import in Python In this article, we will learn how to do Lazy import in Python. For this, let's first understand the lazy import. What is Lazy Import? It is a feature of the Pyforest module that allows the user to perform the task without adding libraries to the code snippet as the task of this function is to add t
5 min read
Create and Import modules in Python In Python, a module is a self-contained Python file that contains Python statements and definitions, like a file named GFG.py, can be considered as a module named GFG which can be imported with the help of import statement. However, one might get confused about the difference between modules and pac
3 min read
Built-in Modules in Python Python is one of the most popular programming languages because of its vast collection of modules which make the work of developers easy and save time from writing the code for a particular task for their program. Python provides various types of modules which include Python built-in modules and ext
9 min read
Python Fire Module Python Fire is a library to create CLI applications. It can automatically generate command line Interfaces from any object in python. It is not limited to this, it is a good tool for debugging and development purposes. With the help of Fire, you can turn existing code into CLI. In this article, we w
3 min read
Python Module Index Python has a vast ecosystem of modules and packages. These modules enable developers to perform a wide range of tasks without taking the headache of creating a custom module for them to perform a particular task. Whether we have to perform data analysis, set up a web server, or automate tasks, there
4 min read
External Modules in Python Python is one of the most popular programming languages because of its vast collection of modules which make the work of developers easy and save time from writing the code for a particular task for their program. Python provides various types of modules which include built-in modules and external m
5 min read
Importlib package in Python In this article, we are going to know about the Importlib package in the Python programming language. The importlib package is primarily utilized by Python applications for dynamic imports during runtime. In layman's terms, it allows the user to load modules as he/she discovers them. This package ha
6 min read
Python Modules Python Module is a file that contains built-in functions, classes,its and variables. There are many Python modules, each with its specific work.In this article, we will cover all about Python modules, such as How to create our own simple module, Import Python modules, From statements in Python, we c
7 min read
Import Modules From Another Folder in Python In this article, we are going to see how to import a module from another folder, While working on big projects we may confront a situation where we want to import a module from a different directory, here we will see the different ways to import a module form different folder. It can be done in two
2 min read
How to Import Local Modules with Python In Python, modules are self-contained files with reusable code units like functions, classes, and variables. Importing local modules allows for organizing the codebase effectively, enhance maintainability, and enhances code reuse. In this article, we will understand how to import local modules with
3 min read