Python from Keyword
The Python from keyword is used to import a specific section from a modules, classes or functions. It is a case-sensitive keyword. Without import keyword we cannot use the from because both are interdependent and raise a SyntaxError.
Usage
Following is the usage of the Python from keyword −
from <module> import <function>
Where,
- module is the name of the module.
- function is the function we need to import.
Example
Following is a basic example of the Python from keyword −
# Importing specific functions
from math import sqrt, pow
# Using the imported functions
print("Square root of 81 is:", sqrt(81))
print("5 to the power of 3 is:", pow(5, 3))
Output
Following is the output of the above code −
Square root of 81 is: 9.0 5 to the power of 3 is: 125.0
Using the from Keyword Without 'import'
When we use from keyword without the import keyword it will raise an SyntaxError.
Example
In the following example we have not used import keyword along with from −
# Importing the datetime class from the datetime module from datetime datetime print(datetime.now())
Output
Following is the output of the above code −
File "/home/cg/root/47560/main.py", line 2
from datetime datetime
^^^^^^^^
SyntaxError: invalid syntax
Using the from Keyword to import an Entire Module
We can also import all the functions from a module using from keyword and import followed by asterisk[*].
Example
Here, is an example to import all the functions from a module using from keyword −
from math import *
print("The remainder of 16 when divided by 7 :",remainder(16,7))
print("The sine value of 90:",sin(90))
Output
Following is the output of the above code −
The remainder of 16 when divided by 7 : 2.0 The sine value of 90: 0.8939966636005579
Using from Keyword with 'as'
We can also use as keyword along with from to make a selected name for a particular function.
Example
Following is an example of, usage of from keyword along with as keyword −
# Importing a class and renaming it
from datetime import datetime as dt
# Using the renamed class
print("Current date and time:", dt.now())
Output
Following is the output of the above code −
Current date and time: 2024-08-07 11:54:06.534770
python_keywords.htm