Typer

Language: Python

CLI/Utils

Typer was created by Sebastián Ramírez, the author of FastAPI, to make building CLI apps as easy as building web APIs with FastAPI. It emphasizes simplicity, automatic documentation, and type safety while being fully compatible with Python’s type hints.

Typer is a modern Python library for building command-line interface (CLI) applications. It leverages Python type hints to automatically generate help messages, validate inputs, and provide a smooth developer experience.

Installation

pip: pip install typer[all]
conda: conda install -c conda-forge typer

Usage

Typer allows you to define commands and options as Python functions with decorators. It automatically generates help pages, validates input types, and integrates easily with modern Python codebases.

Simple CLI command

import typer

def main():
    typer.echo('Hello, Typer!')

if __name__ == '__main__':
    typer.run(main)

Defines a simple command-line program that prints 'Hello, Typer!' when executed.

Command with options

import typer

def greet(name: str = 'World'):
    typer.echo(f'Hello, {name}!')

if __name__ == '__main__':
    typer.run(greet)

Adds an optional parameter `name` to the CLI command, defaulting to 'World'. Typer automatically validates input and generates help text.

Multiple commands using Typer app

import typer
app = typer.Typer()

@app.command()
def hello():
    typer.echo('Hello!')

@app.command()
def goodbye():
    typer.echo('Goodbye!')

if __name__ == '__main__':
    app()

Defines a Typer application with multiple commands using the `@app.command()` decorator.

Type validation and conversion

import typer

def square(number: int):
    typer.echo(number ** 2)

if __name__ == '__main__':
    typer.run(square)

Automatically validates that `number` is an integer and computes its square. Typer will raise an error if input cannot be converted.

Using Enum for choices

from enum import Enum
import typer

class Color(str, Enum):
    red = 'red'
    green = 'green'
    blue = 'blue'

def favorite(color: Color):
    typer.echo(f'Your favorite color is {color}')

if __name__ == '__main__':
    typer.run(favorite)

Restricts input to predefined choices using Python Enums and provides automatic help messages.

Error Handling

ValueError: Ensure input types match function annotations. Typer automatically handles conversion and raises errors if inputs are invalid.
typer.Exit: Use `raise typer.Exit(code=...)` to exit gracefully with a specific exit code.

Best Practices

Use Python type hints to enable automatic validation and documentation.

Organize multiple commands with a Typer app instance instead of standalone functions.

Leverage default values and Enums to guide user input.

Use `typer.echo()` instead of `print()` for consistent CLI output.

Combine Typer with rich or colorama for styled terminal outputs.