The from
keyword in Python is used to import specific parts of a module. It allows you to bring only the needed functionalities into your code, improving readability and efficiency. It’s typically paired with the import keyword.
Syntax
from module_name import specific_item
module_name
: The name of the module you want to import from.specific_item
: The specific class, function, or variable to import from the module.
You can also use the *
wildcard to import all items from a module:
from module_name import *
Why Use from?
- Selective Imports: Only import what you need to reduce memory usage and avoid polluting the namespace.
- Simplified Access: Access imported items directly without prefixing them with the module name.
- Improves Readability: Makes the code cleaner and more readable by importing specific items.
Common Scenarios
1. Importing a Specific Function
from math import sqrt
# Use the imported sqrt function
result = sqrt(16)
print(result)
Output:
4.0
2. Importing Multiple Items
from math import sqrt, pow
# Use the imported sqrt and pow functions
result1 = sqrt(25)
result2 = pow(2, 3)
print(result1, result2)
Output:
5.0 8.0
3. Importing All Items
from math import *
# Use various math functions without prefixing with math
result = sin(pi / 2)
print(result)
Output:
1.0
4. Renaming Imports
You can rename an imported item using the as keyword for clarity or to avoid naming conflicts.
from math import sqrt as square_root
# Use the renamed function
result = square_root(9)
print(result)
Output:
3.0
5. Importing from Custom Modules
If you have a custom Python file (module), you can import specific items from it.
File: my_module.py
def greet(name):
return f"Hello, {name}!"
Main Script:
from my_module import greet
# Use the imported greet function
print(greet("Alice"))
Output:
Hello, Alice!
6. Handling Name Conflicts
If a function or variable in the module conflicts with a name in your code, use from with as to resolve the issue.
from math import pi as math_pi
pi = 3.14 # Local variable
print(f"Local pi: {pi}, Math module pi: {math_pi}")
Output:
Local pi: 3.14, Math module pi: 3.141592653589793
Common Scenarios
Selective Imports: Importing only what’s necessary avoids unnecessary overhead.
from datetime import datetime
print(datetime.now())
Output:
Current date and time.
Cleaner Code: Avoids prefixing module names.
from random import randint
print(randint(1, 10))
Output:
A random integer between 1 and 10.
Key Notes
- Avoid from module import * in Large Codebases: Using * imports all items from a module, which can lead to namespace pollution and unexpected conflicts.
- Use as for Clarity: Rename imported items to improve readability or resolve naming conflicts.
- Combine with Standard Imports: Use from imports alongside regular imports for modularity.
By mastering the from
keyword, you can write more modular, efficient, and readable Python code!