Overview
In the previous tutorial, you learned how to use the import statement to load an entire module into a Python program. This tutorial introduces the Python from…import Statement, which lets you import only the specific members that your program needs.
By the end of this guide, you will understand how the Python from…import Statement works and how to use it effectively with both built-in and user-defined modules.
This tutorial covers the following topics:
Quick Navigation
- Introduction: What is the Python
from...importStatement? - Why Use the
from...importStatement? - Syntax of the
from...importStatement - Importing a Single Member
- Importing Multiple Members
- Importing Functions
- Importing Variables
- Wildcard Import (
*) - When to Avoid Wildcard Imports
importvsfrom...import- Common
from...importStatement Errors - Best Practices for Using
from...import - Key Takeaways
Introduction: What is the Python from...import Statement?
The Python from...import Statement is used to import specific members from a Python module instead of importing the entire module. These members can include functions, variables, classes, or constants.
After importing a member, it can be used directly without writing the module name followed by the dot (.) operator. This makes the code shorter and can improve readability, especially when the same member is used repeatedly.
For example, instead of importing the entire math module just to use the sqrt() function, you can import only sqrt() and call it directly whenever it is needed.
Real-World Analogy
Imagine visiting a library to borrow a single book. Instead of taking an entire bookshelf home, you simply borrow the book that you need. It is quicker, more convenient, and easier to manage.
The from...import statement works in a similar way. Rather than importing an entire module, it allows your program to import only the specific members that will be used.
Why Use the from...import Statement?
The standard import statement is suitable for many programs, but writing the module name before every function or variable can become repetitive. The from...import statement provides a cleaner way to import only the members you need.
Using the from...import statement offers several advantages:
- Imports only the required members from a module.
- Reduces the need to repeatedly write the module name.
- Makes code shorter and often easier to read.
- Works with functions, variables, classes, and constants.
- Can improve code clarity when only a few module members are needed.
Although the from...import statement is convenient, it should be used thoughtfully. Importing too many members directly can sometimes make it difficult to identify which module they came from. Later in this tutorial, you will learn the best practices for using this import method effectively.
Syntax of the Python from...import Statement
The basic syntax of the from...import statement consists of the from keyword, the module name, the import keyword, and the member that you want to use.
from module_name import member_name
Syntax Breakdown
| Part | Description |
|---|---|
from |
Specifies the module from which members will be imported. |
module_name |
The name of the built-in or user-defined module. |
import |
Indicates that one or more members will be imported. |
member_name |
The function, variable, class, or constant to import. |
How the Syntax Works
When Python executes a from...import statement, it first locates the specified module and then imports only the requested member into the current program. Unlike the standard import statement, the imported member can be used directly without prefixing it with the module name.
For example, the following code imports only the sqrt() function from the math module.
from math import sqrt
print(sqrt(25))
# Output
5.0
Code Explanation
The from math import sqrt statement imports only the sqrt() function from Python’s built-in math module. Since the function is imported directly, there is no need to write math.sqrt() when calling it.
The statement sqrt(25) calculates the square root of 25 and returns 5.0, which is then displayed on the screen.
Note: The from...import statement imports only the specified members into the current program. The remaining members of the module are not available unless they are imported separately.
Importing a Single Member
In many programs, you may only need one function, class, variable, or constant from a module. Importing the entire module in such cases is unnecessary because your program uses only a small part of it.
The from...import statement allows you to import a single member directly. Once imported, the member can be used by its name without writing the module name and the dot (.) operator.
Syntax
from module_name import member_name
Example: Importing a Single Function
from math import sqrt
print(sqrt(49))
# Output
7.0
Code Explanation
The statement from math import sqrt imports the sqrt() function from the math module.
The statement sqrt(49) calculates the square root of 49 and returns 7.0, which is displayed on the screen.
Importing Multiple Members
Sometimes a program requires more than one member from the same module. Instead of writing separate from...import statements for each member, Python allows multiple members to be imported in a single statement.
Multiple members are separated by commas, making the code shorter and easier to read while keeping the import statement organized.
Syntax
from module_name import member1, member2, member3
Example: Importing Multiple Functions
from math import sqrt, factorial
print(sqrt(64))
print(factorial(5))
# Output
8.0
120
Code Explanation
The statement from math import sqrt, factorial imports the sqrt() and factorial() functions from the math module.
The sqrt(64) function calculates the square root of 64, while factorial(5) calculates the factorial of 5. The program prints 8.0 and 120 on separate lines.
Importing Functions
Functions are among the most commonly imported members in Python. When a module contains only a few functions that your program needs, importing those functions directly can make the code shorter and easier to read.
Example: Importing a Function from a User-defined Module
Suppose you have a Python file named calculator.py.
calculator.py
def add(a, b):
return a + b
def multiply(a, b):
return a * b
Now create another Python file named main.py.
main.py
from calculator import add
print(add(15, 5))
# Output
20
Code Explanation
The from calculator import add statement imports the add() function from the calculator module.
The statement add(15, 5) adds the two numbers and returns 20, which is then displayed on the screen.
Importing Variables
The from...import statement can also be used to import variables defined in a module. This is useful when a module stores reusable values such as configuration settings, constants, or application information that need to be shared across multiple Python files.
Once a variable is imported, it can be accessed directly without prefixing it with the module name.
Example: Importing Variables from a User-defined Module
Suppose you have a Python file named config.py.
config.py
company = "DigiEduTech"
version = "1.0"
Now create another Python file named main.py.
main.py
from config import company
print(company)
# Output
DigiEduTech
Code Explanation
The from config import company statement imports the company variable from the config module.
The print(company) statement displays the value stored in the imported variable, which is DigiEduTech.
Wildcard Import (*)
In some situations, you may want to import every public member from a module instead of importing them one by one. Python allows this by using the wildcard character (*) with the from...import statement.
A wildcard import makes all public functions, variables, classes, and constants from the module directly available in the current program. After the import, these members can be used without writing the module name.
Syntax
from module_name import *
Example: Using Wildcard Import
from math import *
print(sqrt(81))
print(factorial(5))
# Output
9.0
120
Code Explanation
The statement from math import * imports all public members from Python’s built-in math module.
The sqrt(81) function returns 9.0, while factorial(5) returns 120. The program prints both results on separate lines.
When to Avoid Wildcard Imports (*)
Although wildcard imports are supported by Python, they are rarely recommended in real-world projects. Importing every member from a module can make programs more difficult to understand because it becomes unclear where functions and variables originated.
Another drawback is the possibility of name conflicts. If two imported modules contain members with the same name, one member may overwrite the other, leading to unexpected behavior and making debugging more difficult.
Example: Name Conflict
Suppose two different modules contain a function named display().
module1.py
def display():
print("Module 1")
module2.py
def display():
print("Module 2")
main.py
from module1 import *
from module2 import *
display()
# Output
Module 2
Code Explanation
Both modules define a function named display(). After importing everything from module1, the wildcard import from module2 imports another function with the same name.
When display() is called, Python uses the version imported from module2, so the output is Module 2. This demonstrates how wildcard imports can create naming conflicts when different modules contain members with the same name.
import vs from...import
Both the import statement and the from...import statement are used to access code from a module, but they do so in different ways. Choosing the appropriate approach depends on how your program uses the module.
import |
from...import |
|---|---|
| Imports the entire module. | Imports only the selected members. |
Members are accessed using module_name.member_name. |
Imported members are used directly. |
| Clearly shows which module a member belongs to. | Produces shorter and cleaner code when only a few members are needed. |
| Reduces the chance of naming conflicts. | May increase the chance of naming conflicts if many members are imported. |
| Commonly preferred for larger projects. | Useful when only specific functions, variables, or classes are required. |
Example Comparison
Using import
import math
print(math.sqrt(36))
Using from...import
from math import sqrt
print(sqrt(36))
Output
6.0
Code Explanation
Both programs use the sqrt() function from the math module to calculate the square root of 36. The first program calls the function as math.sqrt(), while the second calls it directly as sqrt(). Both produce the same output of 6.0.
Common from...import Statement Errors
The from...import statement is simple to use, but beginners often encounter a few common mistakes while learning it. Understanding these errors will help you identify problems more quickly and write more reliable Python programs.
Below are the most common errors:
The following sections explain each error, why it occurs, and how to fix it.
ImportError
An ImportError occurs when Python finds the module but cannot locate the member that you are trying to import.
from math import square_root
# Output
ImportError: cannot import name 'square_root' from 'math'
Possible reasons include:
- The member name is misspelled.
- The requested function, variable, or class does not exist in the module.
- The member has been removed or renamed.
The correct code is:
from math import sqrt
print(sqrt(25))
Since the math module does not contain a member named square_root, Python raises an ImportError. Importing the correct member, sqrt, resolves the error.
NameError
A NameError usually occurs when you try to use a member that has not been imported.
from math import sqrt
print(factorial(5))
# Output
NameError: name 'factorial' is not defined
The correct approach is:
from math import sqrt, factorial
print(factorial(5))
Since only sqrt() was imported in the first example, Python does not recognize factorial().
Wildcard Import Conflicts
Using wildcard imports (*) from multiple modules can create naming conflicts. When different modules contain members with the same name, it may become difficult to determine which one your program is using.
from module1 import *
from module2 import *
display()
In this example, if both modules define a display() function, the function imported later may replace the earlier one. This can produce unexpected results and make debugging more difficult.
Note: Importing only the required members is generally a safer and more readable approach than using wildcard imports.
Best Practices for Using from...import
The following best practices will help you write cleaner, more readable, and maintainable Python code.
- Import only the functions, variables, classes, or constants your program needs.
- Avoid wildcard imports (
from module import *) because they can cause naming conflicts. - Group import statements together at the beginning of the Python file.
- Remove unused imports to keep your code clean.
- Use the standard
importstatement when your program requires many members from the same module. - Follow a consistent import style throughout your project.
Key Takeaways: from...import Statement
Here are the key points to remember about the Python from...import Statement.
- The Python
from...importStatement imports specific members from a module. - Imported members can be used directly without the module name.
- You can import one or multiple functions, variables, classes, or constants.
- Avoid wildcard imports (
*) because they can cause naming conflicts. - Understanding common import errors makes debugging easier.
- Choose between
importandfrom...importbased on your program’s requirements.
You now understand how to import specific members from Python modules using the from...import statement. In the next tutorial, you will learn how to use the as keyword to create aliases for modules and imported members, making your code shorter and easier to read.