Import Basics
What is Module Import?
In Python, importing modules is a fundamental mechanism for organizing and reusing code. It allows you to access functions, classes, and variables defined in other Python files or libraries.
Basic Import Syntax
Python provides several ways to import modules:
1. Simple Import
import math
result = math.sqrt(16)
2. Import Specific Items
from os import path
current_dir = path.dirname(__file__)
3. Import with Alias
import numpy as np
array = np.array([1, 2, 3])
Import Search Path
Python searches for modules in the following order:
graph LR
A[Current Directory] --> B[PYTHONPATH Directories]
B --> C[Standard Library Directories]
C --> D[Site-packages Directories]
Module Types
Module Type |
Description |
Example |
Built-in Modules |
Pre-installed with Python |
math , os |
Standard Library |
Included with Python installation |
datetime , random |
Third-party Modules |
Installed via pip |
numpy , pandas |
Custom Modules |
Created by developers |
User-defined Python files |
Best Practices
- Use absolute imports
- Avoid circular imports
- Be explicit about what you import
- Use virtual environments with LabEx to manage dependencies
Practical Example
## mymodule.py
def greet(name):
return f"Hello, {name}!"
## main.py
from mymodule import greet
print(greet("LabEx User"))