Python becomes incredibly powerful when you tap into its vast ecosystem of modules and packages. These modules—whether built-in or custom—allow you to reuse code and access powerful functionalities without rewriting everything from scratch.
In this post, we’ll cover everything you need to know about importing modules in Python using import
, from
, and as
, with clear and simple examples.
1. What is a Module?
A module in Python is simply a file that contains Python code—functions, variables, and classes—that you can reuse in other files. Python comes with many built-in modules (like math
, random
, datetime
), and you can also create your own.
2. Using import
The most basic way to use a module is with the import
statement.
# Example 1: Basic import
import math
print(math.sqrt(25)) # Output: 5.0
print(math.pi) # Output: 3.141592653589793
Here, you access module functions and variables using the dot notation (module_name.function_name
).
3. Using from ... import ...
If you want to import specific parts of a module, use from ... import ...
.
# Example 2: Import specific functions
from math import sqrt, pi
print(sqrt(49)) # Output: 7.0
print(pi) # Output: 3.141592653589793
This lets you use the function or variable directly, without the module prefix.
4. Using as
to Rename
You can rename a module or function using the as
keyword. This is helpful for shortening long names or avoiding naming conflicts.
# Example 3: Alias using as
import numpy as np
print(np.array([1, 2, 3]))
# Example 4: Rename function
from math import sqrt as square_root
print(square_root(81)) # Output: 9.0
5. Importing Custom Modules
You can also import your own Python files as modules. Suppose you have a file greetings.py
:
# greetings.py
def say_hello(name):
return f"Hello, {name}!"
# main.py
import greetings
print(greetings.say_hello("Arjun")) # Output: Hello, Arjun!
6. Import All with *
Although not recommended for production code, you can import everything from a module using *
.
# Example 5: Import everything
from math import *
print(sin(pi / 2)) # Output: 1.0
Note: This can make the code less readable and might cause conflicts if two functions have the same name.
7. Module Search Path
When you import a module, Python searches in these locations:
- Current working directory
- Standard library folders
- Third-party packages (installed via pip)
# Check module search paths
import sys
print(sys.path)
8. Summary Table
Syntax | Usage | Example |
---|---|---|
import module |
Import the entire module | import math |
from module import name |
Import specific item | from math import sqrt |
import module as alias |
Import and rename | import pandas as pd |
from module import * |
Import everything | from math import * |
9. Final Thoughts
Understanding how to import modules efficiently can help you build better, cleaner, and more modular Python programs. Stick to importing only what you need, give aliases to long names if needed, and avoid wildcard imports for cleaner, more readable code.