Python Import Basics
Understanding Python Imports
Python imports are fundamental mechanisms for including external modules and packages in your code. They allow you to reuse code, organize projects, and leverage existing libraries efficiently.
Basic Import Syntax
Simple Import
import math
result = math.sqrt(16) ## Importing entire module
Specific Function Import
from math import sqrt
result = sqrt(16) ## Importing specific function
Multiple Imports
from math import sqrt, pow
result = sqrt(pow(2, 3)) ## Multiple function imports
Import Mechanisms
graph TD
A[Python Import Process] --> B[Search Python Path]
B --> C[Locate Module]
C --> D[Load and Execute Module]
D --> E[Make Module Available]
Import Search Paths
Python searches for modules in several predefined locations:
Search Order |
Location |
Description |
1 |
Current Directory |
Immediate project directory |
2 |
PYTHONPATH |
Environment variable paths |
3 |
Standard Library |
Built-in Python modules |
4 |
Site-packages |
Third-party installed packages |
Common Import Practices
Aliasing Imports
import numpy as np ## Common alias for numpy
import pandas as pd ## Common alias for pandas
Relative Imports
from .local_module import function ## Import from same directory
from ..parent_module import class_name ## Import from parent directory
Best Practices
- Use explicit imports
- Avoid circular imports
- Keep import statements at the top of the file
- Use absolute imports when possible
LabEx Recommendation
For comprehensive Python import understanding, LabEx suggests practicing with various import scenarios and exploring module structures systematically.