The from keyword is used to import specific functions, classes, or variables from a module. This allows to use only the required parts of a module without importing the entire module.
from math import sqrt
print(sqrt(25))
Output
5.0
Explanation: statement from math import sqrt imports only the sqrt() function from the math module. After importing it, the function can be called directly using sqrt() without writing math.sqrt().
Syntax
from module_name import item_name
Parameters:
- module_name: The module from which the item is imported.
- item_name: The function, class, variable, or object to import.
Examples
Example 1: Here, we import the sqrt() and pow() functions from the math module.
from math import sqrt, pow
print(sqrt(64))
print(pow(2, 5))
Output
8.0 32.0
Explanation: statement from math import sqrt, pow imports both functions from the math module. They can be called directly without using math.
Example 2: Here, we import the randint() function with the alias random_number.
from random import randint as random_number
print(random_number(1, 10))
Output
10
Explanation: statement from random import randint as random_number imports the randint() function and renames it to random_number. The alias is then used to generate a random integer between 1 and 10.
Example 3: Here, we import all public members of the math module and use the factorial() function directly.
from math import *
print(factorial(5))
Output
120
Explanation: statement from math import * imports all public functions and variables from the math module. After importing them, factorial() can be called directly without using math.factorial().