Last modified: Aug 11, 2025 By Alexander Williams

Python Typer Subcommands and Modular CLI

Python Typer simplifies CLI app development. It uses subcommands for modularity. This article explains how to structure CLI apps with Typer.

What Are Typer Subcommands?

Subcommands break CLI apps into smaller functions. Each subcommand handles a specific task. This improves code organization and usability.

Think of git commands. git commit and git push are subcommands. Typer lets you build similar structures.

Basic Subcommand Example

Here's a simple Typer app with subcommands:


import typer

app = typer.Typer()

@app.command()
def create(name: str):
    typer.echo(f"Creating {name}")

@app.command()
def delete(name: str):
    typer.echo(f"Deleting {name}")

if __name__ == "__main__":
    app()

This creates two subcommands: create and delete.

Running Subcommands

Here's how to use the CLI app:


python app.py create myitem
# Output: Creating myitem

python app.py delete myitem
# Output: Deleting myitem

Modular CLI Structure

For larger apps, split commands into modules. This keeps code clean and maintainable.

First, install Typer if you haven't. See our Typer installation guide.

Step 1: Create Command Modules

Make separate files for related commands. For example:


# file: commands/create.py
import typer

app = typer.Typer()

@app.command()
def user(name: str):
    typer.echo(f"Creating user {name}")

@app.command()
def item(name: str):
    typer.echo(f"Creating item {name}")

Step 2: Combine Commands

Import modules into your main app:


# file: app.py
import typer
from commands.create import app as create_app

app = typer.Typer()
app.add_typer(create_app, name="create")

if __name__ == "__main__":
    app()

Step 3: Use Nested Commands

Now you can run nested commands:


python app.py create user john
# Output: Creating user john

python app.py create item book
# Output: Creating item book

Advanced Subcommand Features

Typer offers powerful subcommand features. Use them for professional CLI apps.

Help Text and Metadata

Add descriptions to subcommands:


app.add_typer(
    create_app,
    name="create",
    help="Create new resources"
)

Shared Options and Arguments

Learn about arguments vs options in Typer. Use them across subcommands.

Type Hints for Validation

Typer uses Python type hints. Our type hints guide explains this feature.

Best Practices

Follow these tips for better CLI apps:

1. Keep commands focused on single tasks

2. Group related commands in modules

3. Use consistent naming conventions

4. Provide clear help messages

Conclusion

Typer subcommands create modular CLI apps. They improve code organization and user experience. Start with simple commands and expand as needed.

For more on command structures, see our single vs multi commands guide.