In Python, there are two ways to import modules: using the import statement and the from statement.
Here's how they differ:
-
import module: This statement imports the whole module, making all its functions, classes, and variables available in your code's namespace. To use any functions, classes, or variables defined in the module, you need to prefix them with the module name followed by a dot (".") character. For example:
import math
x = math.sqrt(4)
In this example, we're importing the whole math module and using the sqrt() function defined in it. We need to prefix the function name with the module name (math.) to use it in our code.
-
from module import function: This statement imports only the specified function (or class, or variable) from the module, making it directly available in your code's namespace. You don't need to prefix the function name with the module name when you use it in your code. For example:
from math import sqrt
x = sqrt(4)
In this example, we're importing only the sqrt() function from the math module, and using it directly in our code without having to prefix it with the module name.
Using from module import function can make your code more concise and readable, especially if you only need to use a few functions from a large module. However, be aware that if you import multiple functions from different modules, you may run into naming conflicts if the function names overlap. In general, it's a good practice to use clear and descriptive function names to avoid naming conflicts, and to use the import module syntax if you need to import multiple functions from a module.