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.
pip install typer[all]conda install -c conda-forge typerTyper 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.
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.
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.
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.
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.
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.
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.