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:

1from module_name import item_name

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:

1from math import sqrt
2
3print(sqrt(25))  # Outputs: 5.0

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.

1from math import sqrt, pi
2
3print("The square root of pi is approximately", sqrt(pi))  # Outputs: The square root of pi is approximately 1.77245385091

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.