Python from
The from keyword in Python is used to import specific items (such as functions, classes, or variables) from a module instead of importing the entire module. It helps keep the code cleaner and avoids unnecessary namespace clutter.
For example, instead of importing the entire math module, only the required functions can be imported.
Syntax
from module_name import name
To import multiple items:
from module_name import name1, name2, ...
To import all public names from a module (not recommended):
from module_name import *
In the syntax:
module_name: The name of the module to import from.name: The specific object(s) (function, class, or variable) to import.- The asterisk (
*) imports all public objects from the module, which can lead to namespace conflicts and reduced clarity.
Example 1: Importing a Specific Function
This example demonstrates importing a single function (sqrt) from the math module:
from math import sqrt# Using the imported function directlyresult = sqrt(16)print(result)
The output of this code is:
4.0
Example 2: Importing Multiple Functions
This example shows how to import more than one function from the same module:
from math import ceil, floorprint(ceil(4.2))print(floor(4.8))
The output of this code is:
54
Example 3: Using from for Relative Imports
The from keyword can also be used with relative imports inside packages, such as:
from . import utilsfrom ..helpers import format_data
- Relative imports use dots (
.) to indicate the current and parent packages. - Explicit imports using
fromenhance code readability and prevent unnecessary components from being loaded.
Codebyte Example
The following example illustrates importing multiple functions (sqrt, pow) and using them directly in a program:
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn Python on Codecademy
- Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
- Includes 6 Courses
- With Professional Certification
- Beginner Friendly.75 hours
- Learn the basics of Python 3.12, one of the most powerful, versatile, and in-demand programming languages today.
- With Certificate
- Beginner Friendly.24 hours