Open In App

Python "from" Keyword

Last Updated : 06 Mar, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

The from keyword in Python is mainly used for importing specific parts of a module rather than the entire module. It helps in making the code cleaner and more efficient by allowing us to access only the required functions, classes, or variables.

Here's an example.

Python
# Importing only sqrt function of math modeule
from math import sqrt

print(sqrt(25))

Output
5.0

In the above code, instead of importing the entire math module, we only import the sqrt function with the help of "from" keyword and use it directly using "sqrt()" without needing to write math.sqrt()

Syntax:

from module_name import specific_function_or_class

module_name : name of the module needed.

specific_function_or_class: name of the required specific function or class from the module.

Let's explore how to use "from" keyword with different examples.

To import a Specific Function/Class

Python
from math import sqrt

print(sqrt(2025))

Output
45.0

To Import Multiple Functions/Classes

Instead of importing a single function or class from a module, we can import multiple function and classes with the help of "from" keyword. Here's how,

Python
from math import sqrt, ceil, floor

print(sqrt(2025))
print(ceil(7/2))    # 7/2 is 3.5
print(floor(7/2))

Output
45.0
4
3

In the above code we have imported multiple functions from the math module and used them directly. It increases the flexibility and efficiency.

Importing Everything from a Module

Although it's not recommended to import everything from a module while coding, but in-case if we are required to do it, we can do it by using '*' operator and simple use any function or class required from that module.

Python
from math import *

print(sqrt(25))

Output
5.0

Using from for Relative Imports In Packages

Relative imports are used inside packages to import modules from the same or different levels of the package hierarchy. It's done with the help of "from" keyword. Let's ubderstand with an example.

Suppose we have the following package structure:


mypackage/

│── __init__.py

│── module_a.py

│── module_b.py

│── subpackage/

│── __init__.py

│── module_c.py

Now, let's say module_b.py wants to import a function named "func" from module_a.py. Here's how we can do it:

Python
from .module_a import func

Explanation:

  • Using "from", we can navigate through the package.
  • .module_a: the single dot ( . ) means in the "current package", module_a.
  • import func, imports the function - "func".

Next Article
Article Tags :
Practice Tags :

Similar Reads