Importing Techniques
2 min read ·
Importing modules correctly is one of the most important concepts in Python because it directly affects readability, performance, and maintainability of your code.
import module
This is the most basic and recommended way.
- Imports the entire module
- Access everything using
module_name.
Note
This approach avoids naming conflicts and keeps code clear.
import module as alias
You can rename a module to make it shorter.
- Useful when module name is long
- Common in real world projects
from module import name
Import only specific functions or variables.
- No need to use module prefix
- Cleaner syntax
from module import *
Caution
This imports everything into current namespace and can create confusion or overwrite existing names. Avoid in production code.
Import Multiple Items
You can import multiple modules in one line.
Or:
Import Order and Best Practices
Python follows a standard import order for clean code.
- Built in modules
- Third-party modules
- User-defined modules
Best Practices
- Always use clear and readable imports
- Avoid
import * - Use alias only when necessary
- Keep imports at the top of the file
- Group imports properly
Pro Tip
Following proper import structure makes your code look professional and easier to understand.
Exercise
Create a program where:
- You import math using alias
- Import sqrt using from
- Use random module
Print results using all three methods.