A Comprehensive Guide to Typer for Building Command Line Interfaces

Introduction to Typer

Typer is a library for creating Command Line Interface (CLI) applications that draws upon the
strengths of Python’s click, fastAPI, and pydantic.
It aims to ease the development of CLIs with minimal code and highly rich functionality.

Features of Typer

Typer is type-friendly and automatically generates a user-friendly CLI from your functions.
Below are some of the useful APIs within Typer:

Simple CLI Application

A simple example to get started:

  import typer
def main(name: str):
    typer.echo(f"Hello {name}")

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

Optional Arguments and Default Values

Creating commands with optional arguments:

  import typer
def main(name: str = "World"):
    typer.echo(f"Hello {name}")

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

Using Callbacks

Callback functions to validate options:

  import typer
def validate_name(name: str):
    if not name.isalpha():
        raise typer.BadParameter("Name should be alphabetic")

def main(name: str = typer.Option(..., callback=validate_name)):
    typer.echo(f"Hello {name}")

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

Using Typer for Enum Types

Defining and using Enums with Typer:

  import typer from enum import Enum
class Color(str, Enum):
    red = "red"
    green = "green"
    blue = "blue"

def main(color: Color):
    typer.echo(f"Color is {color}")

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

Nested Commands

Creating nested commands with Typer:

  import typer
app = typer.Typer()
@app.command() def start():
    typer.echo("Starting the app")

@app.command() def stop():
    typer.echo("Stopping the app")

if __name__ == "__main__":
    app()
 

Full Example: Todo Application

An example CLI application using the introduced APIs:

  import typer from typing import Optional from enum import Enum
app = typer.Typer()
class Priority(str, Enum):
    low = "low"
    medium = "medium"
    high = "high"

todos = []
@app.command() def add(task: str, priority: Priority = Priority.low):
    todos.append({"task": task, "priority": priority})
    typer.echo(f"Added task: {task} with {priority} priority")

@app.command() def list_tasks():
    for todo in todos:
        typer.echo(f"Task: {todo['task']}, Priority: {todo['priority']}")

if __name__ == "__main__":
    app()
 

By following the examples provided, you can start building scalable CLI applications with Typer in no time!

Hash: 19cb4ed1d91e113962aee8a64bb8c911ff76946528022843515f886de2665526

Leave a Reply

Your email address will not be published. Required fields are marked *