What is the purpose of ‘from’ and ‘import’ in Python?
In Python, the keywords ‘from’ and ‘import’ are used to bring functions, classes, or variables from other modules.
The keyword “from” is used to import a specific function, class, or variable from a designated module directly into the current namespace for direct use. The syntax is as follows:
from module_name import name
For example, import the sqrt function from the math module.
from math import sqrt
This way you can directly use the sqrt function without needing to call math.sqrt.
The “import” keyword is used to bring a whole module into the current namespace. The syntax is as follows:
import module_name
For example, importing the math module:
import math
This allows you to use all functions, classes, and variables from the math module, but you need to call them with the math prefix.
In summary, ‘from’ is used to import specific functions, classes, or variables, while ‘import’ is used to import entire modules. By using these two keywords, we can incorporate code from other modules in Python, increasing code reusability and maintainability.