Import discipline

From oborchers/fractional-cto · View interactive version

Import discipline is an AI agent skill from the GitHub repository oborchers/fractional-cto. This skill should be used when the user is organizing imports, writing require/use/include statements, fixing import ordering, dealing with circular dependencies, or when a file has disordered, ungrouped, or inconsistent imports. Covers import grouping, sorting, separation, and the rule that imports

How to use this skill

Skill file

Imports Are the Table of Contents

The import block is the first thing a reader sees after the module docstring. It answers the most fundamental question about any file: what does this depend on? A disordered import block is like a book with a scrambled table of contents — it forces the reader to scan every line to understand the file's dependencies. This is not a cosmetic concern. It is a readability failure.

The rules are simple, universal, and non-negotiable: group by origin, separate groups with blank lines, alphabetize within groups, import only what you use, never import everything.

Universal Grouping Order

Every language has the same conceptual hierarchy. Adapt the specifics; preserve the structure.

Group 1: Standard library / built-in modules
          (blank line)
Group 2: Third-party / external packages
          (blank line)
Group 3: Internal / project-level modules
          (blank line)
Group 4: Relative / sibling imports

Rules that apply everywhere:

  1. One blank line between each group. Not two. Not zero. One. This is the visual separator that lets the eye jump between dependency categories instantly.
  2. Alphabetized within each group. Not by "importance," not by "order I wrote them," not by "how often I use them." Alphabetical. This makes merge conflicts smaller, makes it obvious when something is missing, and eliminates all subjective ordering debates forever.
  3. One import per line. Multi-import lines hide dependencies and make diffs noisy. The exception is destructured imports in JavaScript/TypeScript where a single module provides multiple named exports — but even then, if it exceeds ~4 names, split across lines.
  4. No unused imports. Not "I might need this later." Not "the linter will catch it." Delete it now. An unused import is a lie in the table of contents — it claims the file depends on something it does not.

Python

Python's import conventions are well-established. Tools like isort and ruff enforce them automatically — but you must understand the rules to configure the tools correctly and to catch what they miss.

Grouping order:

# 1. __future__ imports (always first, always alone)
from __future__ import annotations

# 2. Standard library
import os
import sys
from collections import defaultdict
from pathlib import Path

# 3. Third-party packages
import httpx
import pydantic
from fastapi import FastAPI, HTTPException
from sqlalchemy import Column, Integer, String

# 4. Internal / project modules
from myapp.config import Settings
from myapp.database import get_session
from myapp.models import User

# 5. Relative / sibling imports
from .exceptions import NotFoundError
from .schemas import UserCreate, UserResponse

Critical Python rules:

TypeScript

TypeScript imports have more variety (node builtins, npm packages, workspace packages, path aliases, relative paths) but the same grouping principle applies.

Grouping order:

// 1. Node built-in modules
import fs from "node:fs";
import path from "node:path";

// 2. External packages (npm)
import express from "express";
import { z } from "zod";

// 3. Organization-scoped packages
import { logger } from "@myorg/logger";
import { validateRequest } from "@myorg/middleware";

// 4. Internal path aliases (@/ or ~/)
import { db } from "@/database";
import { UserModel } from "@/models/user";
import { config } from "@/config";

// 5. Relative imports
import { NotFoundError } from "./errors";
import { userSchema } from "./schemas";
import type { UserCreateInput } from "./types";

Critical TypeScript rules:

Go

Go's import conventions are the strictest and the best-tooled. goimports handles formatting automatically, but you must still structure imports correctly for readability.

Grouping order:

import (
	// 1. Standard library
	"context"
	"fmt"
	"net/http"
	"time"

	// 2. External packages
	"github.com/gin-gonic/gin"
	"github.com/jackc/pgx/v5"
	"go.uber.org/zap"

	// 3. Internal packages
	"myapp/internal/config"
	"myapp/internal/database"
	"myapp/internal/models"
)

Critical Go rules:

Inline and Lazy Imports

Inline imports (importing inside a function instead of at the top of the file) are a code smell by default. They break the "table of contents" contract — the reader cannot see all dependencies at a glance.

Acceptable ONLY in these cases:

  1. Documented circular dependency. Two modules that must reference each other, where a top-level import creates a cycle. The inline import breaks the cycle. Always add a comment:

```python

def get_user_orders(user_id: str) -> list:

# Inline import to break circular dependency: models -> services -> models

from myapp.services.orders import OrderService

return OrderService.find_by_user(user_id)

```

  1. Conditional heavy import. A module that is expensive to load (e.g., ML model, large data file) and only needed in a rarely-executed code path:

```python

def generate_report():

# Lazy import: pandas is only needed for reporting, not on every request

import pandas as pd

...

```

  1. Optional dependency. A feature that works with or without a package:

```python

try:

import orjson as json # Faster JSON if available

except ImportError:

import json

```

In all three cases, the comment explaining WHY is mandatory. An inline import without an explanation is a violation.

Star Imports and Wildcards

from module import * is banned. In every language. Without exception.

Why:

# BAD — where does Request come from? Flask? Django? A local module?
from flask import *
from myapp.models import *

# GOOD — every dependency is traceable
from flask import Flask, Request, jsonify
from myapp.models import User, Order
// BAD
export * from "./models";
export * from "./utils";
// If models and utils both export "validate", which one wins?

// GOOD — explicit re-exports
export { User, Order } from "./models";
export { formatDate, parseId } from "./utils";

Re-Exports

Centralize public APIs through index files, but make them explicit.

# myapp/models/__init__.py
from .user import User
from .order import Order
from .product import Product

__all__ = ["Order", "Product", "User"]  # Alphabetized. Always.
// models/index.ts
export { Order } from "./order";
export { Product } from "./product";
export { User } from "./user";
// Alphabetized. Explicit. No star re-exports.

Unused Imports

Delete them. Immediately. Not after the feature is done. Not when the linter runs. Now.

An unused import is:

"But I might need it later" is not a reason. Version control exists. Import it again when you need it. The 3 seconds of re-typing are cheaper than the permanent tax of a false dependency.

Examples

Working implementations in examples/:

Review Checklist

When writing or reviewing import blocks:

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.