from...import... Statement
Python is a vast language with a massive standard library and thousands of additional modules available on the Python Package Index (PyPI). However, not all of these modules are needed by every program. Hence, Python offers functionality to import specific items from a module for use in your code. This is done using the from...import...
statement.
What is the from…import… Statement?
The from...import...
statement in Python is a way to import specific attributes or functions from a module rather than importing the whole module. By using this statement, you can make your code more efficient by only importing what you need and making your program run faster.
The syntax for from…import… statement is as follows:
In the statement above, module_name
is the name of the module you’re importing from, and item_name
is the item (function, class, variable) you’re importing.
How to Use the from…import… Statement
Let’s say you’re working with the math
module, which includes functions like sqrt
(square root), factorial
, and constants like pi
.
If you’re writing a program that only needs to calculate the square root of numbers, you don’t need to import the entire math
module. You can import only the sqrt
function.
Here is how you would do this:
In the example above, the square root function sqrt
is imported from the math
module, and we’re able to use it directly without prefixing it with the module name.
Importing Multiple Items
You can import more than one item from a module by separating them with commas.
In this example, both the sqrt
function and the pi
constant are imported from the math
module.
Note
The from...import...
statement can make your code easier to read and more efficient, but it can also make it harder to debug if the imported items clash with variables in your own code since you don’t need to include the module name as a prefix.