While the standard import module_name
statement brings the entire module's functionality into your program, you always need to prefix the items you use with the module's name (like math.pi
or random.randint()
). This is generally a good practice because it keeps the origin of names clear and prevents accidental naming conflicts.
However, sometimes you might only need one or two specific functions or variables from a module, and you plan to use them frequently. Typing the module name repeatedly can feel cumbersome. Python provides an alternative syntax, from ... import
, specifically for this purpose. It allows you to import specific names directly into your script's current namespace, letting you use them without the module prefix.
from ... import
SyntaxThe basic structure looks like this:
from module_name import name1, name2, ...
Let's revisit our math
module example. Suppose we only need the sqrt
function (for square roots) and the constant pi
.
Previously, we would do:
import math
radius = 5
area = math.pi * (radius ** 2)
hypotenuse = math.sqrt(3**2 + 4**2)
print(f"Area: {area}")
print(f"Hypotenuse: {hypotenuse}")
Using from ... import
, we can write:
from math import pi, sqrt
radius = 5
# Notice no 'math.' prefix is needed now
area = pi * (radius ** 2)
hypotenuse = sqrt(3**2 + 4**2)
print(f"Area: {area}")
print(f"Hypotenuse: {hypotenuse}")
# Output:
# Area: 78.53981633974483
# Hypotenuse: 5.0
As you can see, pi
and sqrt
are now available directly, making the code slightly shorter.
The convenience of from ... import
comes with a potential cost: namespace pollution and reduced clarity.
A namespace is like a dictionary where Python stores the names (of variables, functions, classes) currently defined and accessible. When you use import math
, Python creates an entry for math
, and all its contents are accessed through that math
entry (e.g., math.pi
). The names inside the math
module don't directly mix with the names defined in your script.
However, when you use from math import pi
, the name pi
itself is added directly to your script's main namespace. If you already had a variable named pi
in your script, it would be overwritten by the one imported from math
, potentially leading to unexpected behavior or errors.
Consider this:
# Define our own 'sqrt' function (perhaps poorly)
def sqrt(number):
print(f"Maybe finding the square root of {number}?")
return number / 2 # Incorrect calculation!
# Let's calculate something else unrelated first
result1 = sqrt(100)
print(f"Our initial sqrt(100) result: {result1}")
# Now, import the real sqrt from the math module
from math import sqrt
# Try using sqrt again - which one runs?
result2 = sqrt(100)
print(f"Result after importing math.sqrt: {result2}")
# Output:
# Maybe finding the square root of 100?
# Our initial sqrt(100) result: 50.0
# Result after importing math.sqrt: 10.0
The from math import sqrt
statement overwrote our custom sqrt
function with the one from the math
module. While this example is contrived, in larger projects with many variables and functions, accidentally overwriting a name becomes a real possibility if you import many names directly.
from module import *
(Use with Caution!)Python offers a variation: from module_name import *
. The asterisk (*
) is a wildcard meaning "import everything".
# Caution: Generally discouraged!
from math import *
# Now all names from math are directly available
print(pi)
print(sqrt(16))
print(cos(0))
# Output:
# 3.141592653589793
# 4.0
# 1.0
This imports all public names from the specified module directly into your current namespace. While it might seem convenient for interactive use or very small scripts, it is strongly discouraged in larger programs. Why?
sqrt(100)
doesn't immediately tell you if it's a built-in function, defined in the current file, or imported from math
(or some other module imported using *
). The standard import math
followed by math.sqrt(100)
leaves no ambiguity.Use from module import *
sparingly, if at all. Standard practice favors the explicitness of import module_name
or the selective nature of from module_name import specific_name
.
from ... import ... as ...
What if you want to import a specific name, but it conflicts with an existing name in your script, or you simply prefer a different name? You can use as
to create an alias, just like you can with the standard import
statement.
from math import pi as mathematical_pi
# Use our own variable named 'pi'
pi = 3.14 # A less precise version, maybe for specific needs
radius = 5
# Use the aliased import for the precise value
area = mathematical_pi * (radius ** 2)
print(f"Our pi: {pi}")
print(f"Imported pi: {mathematical_pi}")
print(f"Calculated area: {area}")
# Output:
# Our pi: 3.14
# Imported pi: 3.141592653589793
# Calculated area: 78.53981633974483
This gives you the benefit of direct access without the prefix, while also resolving potential name conflicts or allowing for more descriptive naming.
import module_name
: This is the most common and generally recommended approach.
module_name.function()
comes from).from module_name import name1, name2
: Use this when:
module_name.
becomes distracting.as
.from module_name import name as alias
: Useful to prevent naming conflicts or to shorten a long name when using from ... import
.from module_name import *
: Avoid this in production code or any script of significant size due to namespace pollution and readability issues. It might be acceptable for quick tests in an interactive Python session.Understanding these different ways to import code is fundamental to working effectively with modules and building well-structured Python programs. As you start using Python's standard library and third-party packages, you'll constantly be making choices about how to best import the functionality you need.
© 2025 ApX Machine Learning