Tutorial

How to Split a Monolithic Python CLI (2026)

When and how to split a 4K+ LOC single-file Python CLI: coupling-driven decision, module-per-subcommand pattern.

An r/Python post: 4K LOC single-file CLI with 18 subcommands, asking when to split. This walks the framework and the split.

Prerequisites

  • Python CLI codebase
  • Tests in a separate directory
  • Clear list of subcommands

Walkthrough

Step 1: Audit subcommand coupling

Do they share state heavily? Or are they mostly independent?

Python
# Per subcommand: list shared imports, shared state, shared helpers.

Step 2: Decide based on coupling + navigability

Not LOC.

Text
# Decision: 'I can't navigate it' or 'subcommand has 500+ LOC of independent logic' = split.

Step 3: Plan the package layout

Module-per-subcommand.

Text
# tool/
#   __init__.py
#   __main__.py     # argparse dispatcher
#   shared/
#   commands/
#     analyze.py
#     migrate.py
# tests/

Step 4: Move shared utils to shared/

Anything called by 2+ subcommands.

Python
# Move: parse_yaml(), call_api(), pretty_print().

Step 5: Move each subcommand to commands/<name>.py

Imports shared utils.

Python
# commands/analyze.py:
# from tool.shared.io import parse_yaml
# def analyze_cmd(args): ...

Step 6: Update __main__.py to dispatch

argparse subparsers route to commands/<name>.py.

Python
# import importlib
# subcommand = importlib.import_module(f'tool.commands.{args.command}')
# return subcommand.run(args)

Step 7: Run all existing tests

Should pass without behavior changes.

Bash
# pytest tests/

Python Example

Python
# A 4K LOC single-file with 18 subcommands typically splits in 3-6 hours.

JavaScript Example

JavaScript
// Pattern transfers to Node CLIs.

Expected Output

JSON
Modular Python CLI with shared utils + per-subcommand modules.

Related Tutorials

Frequently Asked Questions

Most developers complete this tutorial in 15 to 30 minutes. You will need a Scavio API key (free tier works) and a working Python or JavaScript environment.

Python CLI codebase. Tests in a separate directory. Clear list of subcommands. A Scavio API key gives you 500 free credits per month.

Yes. The free tier includes 500 credits per month, which is more than enough to complete this tutorial and prototype a working solution.

Scavio has a native LangChain package (langchain-scavio), an MCP server, and a plain REST API that works with any HTTP client. This tutorial uses the raw REST API, but you can adapt to your framework of choice.

Start Building

When and how to split a 4K+ LOC single-file Python CLI: coupling-driven decision, module-per-subcommand pattern.