Python Import Basics
Understanding Python Imports
Python's import system is a fundamental mechanism for organizing and reusing code across different modules and packages. When you want to use functions, classes, or variables defined in another Python file, you'll need to use the import
statement.
Basic Import Syntax
There are several ways to import modules in Python:
## Import entire module
import math
## Import specific function or class
from os import path
## Import multiple items
from datetime import datetime, timedelta
## Import all items (not recommended)
from sys import *
Import Search Path
Python uses a specific search path to locate modules:
graph TD
A[Current Directory] --> B[PYTHONPATH Environment Variable]
B --> C[Standard Library Directories]
C --> D[Site-packages Directories]
Module Types
Module Type |
Description |
Example |
Built-in Modules |
Comes with Python installation |
sys , os |
Standard Library |
Included with Python |
datetime , json |
Third-party Modules |
Installed via pip |
numpy , pandas |
Local Modules |
Created by developers |
Your own .py files |
Best Practices
- Use absolute imports
- Avoid circular imports
- Be explicit about what you're importing
- Use virtual environments with LabEx to manage dependencies
Example Project Structure
my_project/
โ
โโโ main.py
โโโ utils/
โ โโโ __init__.py
โ โโโ helper.py
โโโ models/
โโโ __init__.py
โโโ user.py
In this structure, imports would look like:
from utils.helper import some_function
from models.user import User
Common Import Scenarios
- Importing from the same directory
- Importing from parent directories
- Importing third-party libraries
- Handling relative imports
By understanding these basics, you'll be well-equipped to manage Python imports effectively.