Project Structure
Modules & Imports
2 min read
Modules let you organize code into separate files. Understanding imports is essential for working with Python libraries and your own code.
Import Basics
# Import entire module
import json
data = json.loads('{"key": "value"}')
# Import specific items
from json import loads, dumps
data = loads('{"key": "value"}')
# Import with alias
import numpy as np
arr = np.array([1, 2, 3])
# Import everything (avoid this!)
from json import * # Hard to track what's imported
Your Own Modules
Any .py file is a module. Create helpers.py:
# helpers.py
def format_prompt(text):
return f"User: {text}"
API_VERSION = "v1"
Use it in another file:
# main.py
from helpers import format_prompt, API_VERSION
prompt = format_prompt("Hello!")
print(f"Using API {API_VERSION}")
Relative Imports
Within a package, use relative imports:
my_agent/
├── __init__.py
├── core.py
└── tools/
├── __init__.py
└── search.py
# In tools/search.py
from ..core import AgentCore # Go up one level
from . import utils # Same directory
Common Import Patterns
# Standard library
import os
import json
from pathlib import Path
from typing import List, Dict, Optional
# Third-party
import requests
from dotenv import load_dotenv
# AI libraries
from openai import OpenAI
from langchain.agents import create_react_agent
# Your modules
from .config import settings
from .tools import SearchTool
Avoiding Circular Imports
# BAD: a.py imports b.py, b.py imports a.py
# This causes errors!
# SOLUTION 1: Import inside function
def process():
from .other_module import helper # Import when needed
return helper()
# SOLUTION 2: Restructure code
# Move shared code to a third module
Import Best Practices
| Do | Don't |
|---|---|
| Group imports (stdlib, third-party, local) | Mix import styles randomly |
| Use absolute imports when possible | Use from x import * |
| Import at file top (usually) | Import same module multiple times |
| Use aliases for long names | Create confusing aliases |
Next, we'll learn how to organize AI projects professionally. :::