Importing Specific Items via From
๐ท๏ธ Modules and Imports / Import Syntax
When you start working with Python, you will often need to use code that other people have written. These pre-built pieces of code are stored in modules and packages. Instead of bringing in an entire module, which can be large and slow down your program, you can use the from keyword to import only the specific functions, classes, or variables you actually need. This keeps your code clean, efficient, and easier to read.
๐ง Why Import Specific Items?
- Saves memory โ You only load what you use, not the entire module.
- Improves readability โ Other engineers can see exactly which parts of a module are being used.
- Avoids naming conflicts โ If two modules have a function with the same name, importing specific items helps you control which one is used.
- Speeds up execution โ Smaller imports mean faster startup times for your scripts.
โ๏ธ Basic Syntax for from ... import
The general pattern is:
from module_name import item_name
You replace module_name with the actual module (like math or os) and item_name with the specific function, class, or variable you want.
Example: - Instead of writing import math and then using math.sqrt(25), you can write from math import sqrt and then use sqrt(25) directly.
Expected behavior: - The function sqrt becomes available in your code without needing the math. prefix. - Only the sqrt function is loaded, not the entire math module.
๐ ๏ธ Importing Multiple Specific Items
You can import several items from the same module in one line by separating them with commas.
Syntax: from module_name import item_one, item_two, item_three
Example: - from datetime import date, datetime, timedelta - This gives you direct access to the date, datetime, and timedelta classes without typing datetime.date, datetime.datetime, etc.
Expected behavior: - All three items are now available in your namespace. - You can use date.today(), datetime.now(), and timedelta(days=1) directly.
๐ต๏ธ Renaming Imported Items with as
Sometimes the imported item has a long name, or it might conflict with another name in your code. You can rename it using the as keyword.
Syntax: from module_name import item_name as new_name
Example: - from statistics import mean as average - Now you can call average([10, 20, 30]) instead of mean([10, 20, 30]).
Expected behavior: - The function mean is imported but renamed to average. - The original name mean is not available in your code.
๐ Comparison: Full Import vs. Specific Import
| Aspect | Full Import (import module) |
Specific Import (from module import item) |
|---|---|---|
| What is loaded | The entire module | Only the specified items |
| How to use | Must use module.item() | Use item() directly |
| Memory usage | Higher | Lower |
| Readability | Clear where the function comes from | Cleaner, but origin is less obvious |
| Best for | Using many items from one module | Using only one or two items |
๐งช Common Pitfalls to Avoid
- Importing too many items โ If you import ten items from a module, you might as well import the whole module. Keep imports minimal.
- Name collisions โ If you import from math import sin and later define your own sin variable, the imported one gets overwritten. Use as to rename if needed.
- Forgetting the module name โ When you use from ... import, you lose the module prefix. This can make code harder to debug if someone else reads it.
โ Best Practices for Engineers
- Import only what you need โ This makes your dependencies explicit and your code faster.
- Group imports logically โ Standard library imports first, then third-party, then your own modules.
- Use meaningful aliases โ If you rename an import, make sure the alias is clear to other engineers.
- Keep imports at the top โ Place all import statements at the beginning of your file for consistency.
๐ Quick Reference
| Goal | Syntax |
|---|---|
| Import one item | from math import sqrt |
| Import multiple items | from os import path, getcwd |
| Import and rename | from json import dumps as serialize |
| Import everything (avoid this) | **from math import *** |
By using from ... import, you write Python code that is precise, efficient, and easy for other engineers to understand. Start small, import only what you need, and your scripts will be cleaner and faster from the very beginning.
The from keyword lets you import only specific functions, classes, or variables from a module instead of importing the entire module.
๐ฏ Example 1: Importing a Single Function
This example shows how to import just one function from a module.
from math import sqrt
result = sqrt(25)
print(result)
๐ค Output: 5.0
๐ฏ Example 2: Importing Multiple Items
This example shows how to import several specific items from the same module.
from math import pi, sin, cos
angle = pi / 4
sine_value = sin(angle)
cosine_value = cos(angle)
print(sine_value)
print(cosine_value)
๐ค Output: 0.7071067811865476
๐ค Output: 0.7071067811865476
๐ฏ Example 3: Importing with an Alias
This example shows how to give an imported item a shorter name using as.
from datetime import datetime as dt
current_time = dt.now()
print(current_time)
๐ค Output: 2025-04-04 14:30:15.123456 (example output โ actual time will vary)
๐ฏ Example 4: Importing a Custom Function from a Local Module
This example shows how to import a specific function from a file you created.
# Assume we have a file named helpers.py with a function called add_numbers
from helpers import add_numbers
total = add_numbers(10, 20)
print(total)
๐ค Output: 30
๐ฏ Example 5: Importing Specific Constants from a Module
This example shows how to import only the constants you need from a module.
from os import name, sep
print("Operating system name:", name)
print("Path separator:", sep)
๐ค Output: Operating system name: nt (or posix on Linux/Mac)
๐ค Output: *Path separator: * (or / on Linux/Mac)
๐ Comparison: import module vs from module import item
| Approach | Code Example | When to Use |
|---|---|---|
import module |
import math then math.sqrt(25) |
When you need many items from the module |
from module import item |
from math import sqrt then sqrt(25) |
When you need only one or two specific items |
When you start working with Python, you will often need to use code that other people have written. These pre-built pieces of code are stored in modules and packages. Instead of bringing in an entire module, which can be large and slow down your program, you can use the from keyword to import only the specific functions, classes, or variables you actually need. This keeps your code clean, efficient, and easier to read.
๐ง Why Import Specific Items?
- Saves memory โ You only load what you use, not the entire module.
- Improves readability โ Other engineers can see exactly which parts of a module are being used.
- Avoids naming conflicts โ If two modules have a function with the same name, importing specific items helps you control which one is used.
- Speeds up execution โ Smaller imports mean faster startup times for your scripts.
โ๏ธ Basic Syntax for from ... import
The general pattern is:
from module_name import item_name
You replace module_name with the actual module (like math or os) and item_name with the specific function, class, or variable you want.
Example: - Instead of writing import math and then using math.sqrt(25), you can write from math import sqrt and then use sqrt(25) directly.
Expected behavior: - The function sqrt becomes available in your code without needing the math. prefix. - Only the sqrt function is loaded, not the entire math module.
๐ ๏ธ Importing Multiple Specific Items
You can import several items from the same module in one line by separating them with commas.
Syntax: from module_name import item_one, item_two, item_three
Example: - from datetime import date, datetime, timedelta - This gives you direct access to the date, datetime, and timedelta classes without typing datetime.date, datetime.datetime, etc.
Expected behavior: - All three items are now available in your namespace. - You can use date.today(), datetime.now(), and timedelta(days=1) directly.
๐ต๏ธ Renaming Imported Items with as
Sometimes the imported item has a long name, or it might conflict with another name in your code. You can rename it using the as keyword.
Syntax: from module_name import item_name as new_name
Example: - from statistics import mean as average - Now you can call average([10, 20, 30]) instead of mean([10, 20, 30]).
Expected behavior: - The function mean is imported but renamed to average. - The original name mean is not available in your code.
๐ Comparison: Full Import vs. Specific Import
| Aspect | Full Import (import module) |
Specific Import (from module import item) |
|---|---|---|
| What is loaded | The entire module | Only the specified items |
| How to use | Must use module.item() | Use item() directly |
| Memory usage | Higher | Lower |
| Readability | Clear where the function comes from | Cleaner, but origin is less obvious |
| Best for | Using many items from one module | Using only one or two items |
๐งช Common Pitfalls to Avoid
- Importing too many items โ If you import ten items from a module, you might as well import the whole module. Keep imports minimal.
- Name collisions โ If you import from math import sin and later define your own sin variable, the imported one gets overwritten. Use as to rename if needed.
- Forgetting the module name โ When you use from ... import, you lose the module prefix. This can make code harder to debug if someone else reads it.
โ Best Practices for Engineers
- Import only what you need โ This makes your dependencies explicit and your code faster.
- Group imports logically โ Standard library imports first, then third-party, then your own modules.
- Use meaningful aliases โ If you rename an import, make sure the alias is clear to other engineers.
- Keep imports at the top โ Place all import statements at the beginning of your file for consistency.
๐ Quick Reference
| Goal | Syntax |
|---|---|
| Import one item | from math import sqrt |
| Import multiple items | from os import path, getcwd |
| Import and rename | from json import dumps as serialize |
| Import everything (avoid this) | **from math import *** |
By using from ... import, you write Python code that is precise, efficient, and easy for other engineers to understand. Start small, import only what you need, and your scripts will be cleaner and faster from the very beginning.
Interactive Views
You are currently in ๐ All-in-One mode. Use the tabs at the top to switch to ๐ Theory Only or ๐ป Code Only views.
The from keyword lets you import only specific functions, classes, or variables from a module instead of importing the entire module.
๐ฏ Example 1: Importing a Single Function
This example shows how to import just one function from a module.
from math import sqrt
result = sqrt(25)
print(result)
๐ค Output: 5.0
๐ฏ Example 2: Importing Multiple Items
This example shows how to import several specific items from the same module.
from math import pi, sin, cos
angle = pi / 4
sine_value = sin(angle)
cosine_value = cos(angle)
print(sine_value)
print(cosine_value)
๐ค Output: 0.7071067811865476
๐ค Output: 0.7071067811865476
๐ฏ Example 3: Importing with an Alias
This example shows how to give an imported item a shorter name using as.
from datetime import datetime as dt
current_time = dt.now()
print(current_time)
๐ค Output: 2025-04-04 14:30:15.123456 (example output โ actual time will vary)
๐ฏ Example 4: Importing a Custom Function from a Local Module
This example shows how to import a specific function from a file you created.
# Assume we have a file named helpers.py with a function called add_numbers
from helpers import add_numbers
total = add_numbers(10, 20)
print(total)
๐ค Output: 30
๐ฏ Example 5: Importing Specific Constants from a Module
This example shows how to import only the constants you need from a module.
from os import name, sep
print("Operating system name:", name)
print("Path separator:", sep)
๐ค Output: Operating system name: nt (or posix on Linux/Mac)
๐ค Output: *Path separator: * (or / on Linux/Mac)
๐ Comparison: import module vs from module import item
| Approach | Code Example | When to Use |
|---|---|---|
import module |
import math then math.sqrt(25) |
When you need many items from the module |
from module import item |
from math import sqrt then sqrt(25) |
When you need only one or two specific items |