Python > Modules and Packages > Modules > Importing Modules (`import` statement)
Selective Module Import
This snippet demonstrates how to import specific functions or constants from a module using the from ... import
statement. This is useful when you only need a few items from a module and want to avoid the verbosity of the basic import
.
Code Example
This code imports only the sqrt
function and the pi
constant from the math
module. You can now use them directly in your code without prefixing them with math.
.
from math import sqrt, pi
# Now you can use sqrt and pi directly without the math. prefix
result = sqrt(25)
print(result) # Output: 5.0
circle_area = pi * 10**2
print(circle_area)
Concepts Behind the Snippet
The from ... import
statement directly imports the specified names into your current namespace. This can make your code more concise but also introduces the risk of naming conflicts if the imported names clash with existing names in your code.
Real-Life Use Case Section
If you're working on a project where you only need a specific function from a large library, selective import can improve code readability by reducing verbosity. For example, if you only need the json.loads
function from the json
module, you can import it directly.
Best Practices
from module import *
. This imports all names from the module into your current namespace, which can lead to naming conflicts and make your code harder to understand.as
if necessary.
When to use them
Use selective imports when you only need a small subset of a module's functionality and you want to avoid the verbosity of the basic import
statement. Be mindful of potential naming conflicts.
Memory Footprint
In theory, selectively importing only parts of a module should reduce the memory footprint compared to importing the entire module. However, in practice, the difference might be negligible for most standard modules, as Python often loads the entire module anyway. The key benefit is more about code clarity and avoiding namespace pollution.
Alternatives
An alternative is basic import (import math
). Another alternative is to import the whole module and use alias import math as m
then use m.sqrt()
Pros
Cons
FAQ
-
What happens if I try to import a name that doesn't exist in the module?
You'll get anImportError
. -
Can I alias an imported name?
Yes, you can use theas
keyword to give an imported name a different alias:from math import sqrt as square_root
. Now you can usesquare_root()
instead ofsqrt()
.