Import vs From Import in Python: Key Differences and Usage
import loads an entire module and requires using the module name to access its contents, while from import loads specific attributes or functions directly into the current namespace, allowing direct use without the module prefix. Use import for clarity and namespace control, and from import for convenience when only a few items are needed.Quick Comparison
This table summarizes the main differences between import and from import in Python.
| Aspect | import | from import |
|---|---|---|
| Syntax | import module | from module import name |
| Namespace | Imports whole module; access via module.name | Imports specific names directly; use name without prefix |
| Memory Usage | Loads entire module | Only imports specified attributes or functions |
| Readability | Clear where names come from | Can be less clear if many names imported |
| Use Case | When many module parts needed or to avoid name conflicts | When only a few items needed for convenience |
Key Differences
The import statement loads the entire module as a single object. You then access functions, classes, or variables using the module's name as a prefix, like module.function(). This keeps your code clear about where each name comes from and avoids naming conflicts.
In contrast, from import brings specific parts of a module directly into your current namespace. This means you can use those parts without the module prefix, which can make code shorter and easier to read when only a few items are needed. However, it can also cause confusion if different modules have items with the same name.
Another difference is that import always loads the full module, while from import only loads the specified attributes or functions. This can have minor effects on memory and startup time, especially with large modules.
Code Comparison
Using import to access a function from a module:
import math result = math.sqrt(16) print(result)
From Import Equivalent
Using from import to access the same function directly:
from math import sqrt result = sqrt(16) print(result)
When to Use Which
Choose import when you want to keep your code clear about where functions or variables come from, especially in large projects or when many names might clash. It helps avoid confusion by always using the module name as a prefix.
Choose from import when you only need a few specific items from a module and want to write shorter, cleaner code without repeating the module name. This is common in scripts or small programs where name conflicts are unlikely.
Key Takeaways
import loads the whole module and requires prefixing names with the module.from import loads specific names directly for easier access without prefixes.import for clarity and to avoid name conflicts in larger codebases.from import for convenience when only a few items are needed.