Typer, build great CLIs. Easy to code. Based on Python type hints.
npx @tessl/cli install tessl/pypi-typer@0.17.0Typer is a Python library for building command-line interface (CLI) applications that leverages Python type hints to automatically generate user-friendly command-line interfaces. Built on top of Click, it provides an intuitive API that allows developers to create CLIs by simply defining functions with typed parameters, automatically generating help text, argument validation, and shell completion.
pip install typerimport typerCommon imports for building CLI applications:
from typer import Typer, Option, ArgumentAdvanced imports with type annotations:
from typer import Typer, Option, Argument, Context
from typer import FileBinaryRead, FileBinaryWrite, FileText, FileTextWriteimport typer
def hello(name: str):
"""Greet someone."""
print(f"Hello {name}")
if __name__ == "__main__":
typer.run(hello)import typer
app = Typer()
@app.command()
def hello(name: str):
"""Greet someone."""
print(f"Hello {name}")
@app.command()
def goodbye(name: str, formal: bool = False):
"""Say goodbye."""
if formal:
print(f"Goodbye Ms. {name}. Have a good day.")
else:
print(f"Bye {name}!")
if __name__ == "__main__":
app()Typer is built on Click and follows a hierarchical command structure:
The library automatically converts Python function signatures into CLI interfaces, using type hints for validation and Click's robust parameter system for advanced configuration.
The main Typer class and utilities for creating and running CLI applications, including simple function runners and URL launchers.
class Typer:
def __init__(
self,
*,
name: Optional[str] = None,
cls: Optional[Type] = None,
invoke_without_command: bool = False,
no_args_is_help: bool = False,
subcommand_metavar: Optional[str] = None,
chain: bool = False,
result_callback: Optional[Callable[..., Any]] = None,
context_settings: Optional[Dict[Any, Any]] = None,
callback: Optional[Callable[..., Any]] = None,
help: Optional[str] = None,
epilog: Optional[str] = None,
short_help: Optional[str] = None,
options_metavar: str = "[OPTIONS]",
add_help_option: bool = True,
hidden: bool = False,
deprecated: bool = False,
add_completion: bool = True,
rich_markup_mode: str = "rich",
rich_help_panel: Optional[str] = None,
pretty_exceptions_enable: bool = True,
pretty_exceptions_show_locals: bool = True,
pretty_exceptions_short: bool = True,
): ...
def command(self, name: Optional[str] = None, **kwargs): ...
def callback(self, **kwargs): ...
def add_typer(self, typer_instance: "Typer", **kwargs): ...
def __call__(self, *args, **kwargs): ...
def run(function) -> None: ...
def launch(url: str, wait: bool = False, locate: bool = False) -> int: ...Functions for configuring command arguments and options with type validation, help text, and advanced input handling.
def Option(
default = ...,
*param_decls: str,
help: Optional[str] = None,
show_default: Union[bool, str] = True,
prompt: Union[bool, str] = False,
confirmation_prompt: bool = False,
hide_input: bool = False,
**kwargs
): ...
def Argument(
default = ...,
*,
help: Optional[str] = None,
show_default: Union[bool, str] = True,
**kwargs
): ...Specialized file type classes for handling different types of file I/O operations in CLI applications.
class FileText(io.TextIOWrapper): ...
class FileTextWrite(FileText): ...
class FileBinaryRead(io.BufferedReader): ...
class FileBinaryWrite(io.BufferedWriter): ...Testing utilities for CLI applications, including a specialized test runner that works with Typer applications.
class CliRunner:
def invoke(
self,
app: Typer,
args: Optional[Union[str, Sequence[str]]] = None,
input: Optional[Union[bytes, str, IO[Any]]] = None,
**kwargs
) -> Result: ...Re-exported Click functions for terminal interaction, styling, and user input/output operations.
def echo(message: Optional[str] = None, **kwargs): ...
def secho(message: Optional[str] = None, **kwargs): ...
def style(text: str, **kwargs) -> str: ...
def prompt(text: str, **kwargs): ...
def confirm(text: str, **kwargs) -> bool: ...
def clear(): ...
def pause(info: str = "Press any key to continue..."): ...Named color constants for use with terminal styling functions.
BLACK: str = "black"
RED: str = "red"
GREEN: str = "green"
YELLOW: str = "yellow"
BLUE: str = "blue"
MAGENTA: str = "magenta"
CYAN: str = "cyan"
WHITE: str = "white"
RESET: str = "reset"
BRIGHT_BLACK: str = "bright_black"
BRIGHT_RED: str = "bright_red"
BRIGHT_GREEN: str = "bright_green"
BRIGHT_YELLOW: str = "bright_yellow"
BRIGHT_BLUE: str = "bright_blue"
BRIGHT_MAGENTA: str = "bright_magenta"
BRIGHT_CYAN: str = "bright_cyan"
BRIGHT_WHITE: str = "bright_white"Core type definitions used throughout the Typer API.
class Context(click.Context):
"""Click context for accessing command state and configuration."""
class CallbackParam(click.Parameter):
"""Parameter class for callback functions."""
# Type definitions for common types used in the API
from typing import Any, Callable, Dict, List, Optional, Type, Union
# Sentinel values and utility functions
Required = ... # Sentinel value for required parameters
def Default(value: Any) -> Any:
"""
Mark a parameter as having a default value.
Args:
value: The default value to use
Returns:
The default value wrapped for Typer's internal use
"""Exception classes for error handling in CLI applications.
class Abort(click.ClickException):
"""Exception to abort command execution."""
class BadParameter(click.ClickException):
"""Exception for invalid parameter values."""
class Exit(click.ClickException):
"""Exception to exit the program with a specific code."""