CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-typer

Typer, build great CLIs. Easy to code. Based on Python type hints.

Overview
Eval results
Files

parameter-configuration.mddocs/

Parameter Configuration

Functions for configuring command-line arguments and options in Typer applications, providing type validation, help text, prompting, and advanced input handling.

Capabilities

Option Configuration

Configure command-line options (flags starting with -- or -) with extensive customization options.

def Option(
    default: Optional[Any] = ...,
    *param_decls: str,
    callback: Optional[Callable[..., Any]] = None,
    metavar: Optional[str] = None,
    expose_value: bool = True,
    is_eager: bool = False,
    envvar: Optional[Union[str, List[str]]] = None,
    shell_complete: Optional[Callable] = None,
    autocompletion: Optional[Callable[..., Any]] = None,
    default_factory: Optional[Callable[[], Any]] = None,
    parser: Optional[Callable[[str], Any]] = None,
    click_type: Optional[click.ParamType] = None,
    show_default: Union[bool, str] = True,
    prompt: Union[bool, str] = False,
    confirmation_prompt: bool = False,
    prompt_required: bool = True,
    hide_input: bool = False,
    count: bool = False,
    allow_from_autoenv: bool = True,
    help: Optional[str] = None,
    hidden: bool = False,
    show_choices: bool = True,
    show_envvar: bool = True,
    case_sensitive: bool = True,
    min: Optional[Union[int, float]] = None,
    max: Optional[Union[int, float]] = None,
    clamp: bool = False,
    formats: Optional[List[str]] = None,
    mode: Optional[str] = None,
    encoding: Optional[str] = None,
    errors: Optional[str] = "strict",
    lazy: Optional[bool] = None,
    atomic: bool = False,
    exists: bool = False,
    file_okay: bool = True,
    dir_okay: bool = True,
    writable: bool = False,
    readable: bool = True,
    resolve_path: bool = False,
    allow_dash: bool = False,
    path_type: Union[None, Type[str], Type[bytes]] = None,
    rich_help_panel: Union[str, None] = None,
) -> Any:
    """
    Define a command-line option.

    Parameters:
    - default: Default value for the option
    - param_decls: Alternative names for the option (e.g., "-v", "--verbose")
    - callback: Function called when option is parsed
    - metavar: Name shown in help for the option's value
    - expose_value: Whether to pass the option value to the command function
    - is_eager: Process this option before others
    - envvar: Environment variable name(s) to read default from
    - shell_complete: Shell completion function
    - autocompletion: Auto-completion function
    - default_factory: Function to generate default value
    - parser: Custom parsing function
    - click_type: Custom Click parameter type
    - show_default: Show default value in help
    - prompt: Prompt user for value if not provided
    - confirmation_prompt: Ask for confirmation when prompting
    - prompt_required: Require value when prompting
    - hide_input: Hide input when prompting (for passwords)
    - count: Count number of times option is used
    - allow_from_autoenv: Allow reading from environment
    - help: Help text for the option
    - hidden: Hide option from help
    - show_choices: Show available choices in help
    - show_envvar: Show environment variable in help
    - case_sensitive: Case sensitive choice matching
    - min/max: Numeric range validation
    - clamp: Clamp numeric values to range
    - formats: DateTime format strings
    - mode: File open mode
    - encoding: File encoding
    - errors: Error handling for file operations
    - lazy: Lazy file opening
    - atomic: Atomic file operations
    - exists: Path must exist
    - file_okay: Allow files
    - dir_okay: Allow directories
    - writable: Path must be writable
    - readable: Path must be readable
    - resolve_path: Resolve path to absolute
    - allow_dash: Allow dash as stdin/stdout
    - path_type: Path string type
    - rich_help_panel: Rich formatting help panel

    Returns:
    OptionInfo instance for use as parameter annotation
    """

Argument Configuration

Configure positional command-line arguments with validation and help text.

def Argument(
    default: Optional[Any] = ...,
    *,
    callback: Optional[Callable[..., Any]] = None,
    metavar: Optional[str] = None,
    expose_value: bool = True,
    is_eager: bool = False,
    envvar: Optional[Union[str, List[str]]] = None,
    shell_complete: Optional[Callable] = None,
    autocompletion: Optional[Callable[..., Any]] = None,
    default_factory: Optional[Callable[[], Any]] = None,
    parser: Optional[Callable[[str], Any]] = None,
    click_type: Optional[click.ParamType] = None,
    show_default: Union[bool, str] = True,
    show_choices: bool = True,
    show_envvar: bool = True,
    help: Optional[str] = None,
    hidden: bool = False,
    case_sensitive: bool = True,
    min: Optional[Union[int, float]] = None,
    max: Optional[Union[int, float]] = None,
    clamp: bool = False,
    formats: Optional[List[str]] = None,
    mode: Optional[str] = None,
    encoding: Optional[str] = None,
    errors: Optional[str] = "strict",
    lazy: Optional[bool] = None,
    atomic: bool = False,
    exists: bool = False,
    file_okay: bool = True,
    dir_okay: bool = True,
    writable: bool = False,
    readable: bool = True,
    resolve_path: bool = False,
    allow_dash: bool = False,
    path_type: Union[None, Type[str], Type[bytes]] = None,
    rich_help_panel: Union[str, None] = None,
) -> Any:
    """
    Define a command-line argument.

    Parameters:
    Similar to Option but for positional arguments. Arguments cannot have
    param_decls, prompt, confirmation_prompt, prompt_required, hide_input,
    count, or allow_from_autoenv parameters.

    Returns:
    ArgumentInfo instance for use as parameter annotation
    """

Usage Examples

Basic Options and Arguments

import typer
from typing import Optional

def main(
    name: str = typer.Argument(..., help="Name of the person to greet"),
    count: int = typer.Option(1, "--count", "-c", help="Number of greetings"),
    polite: bool = typer.Option(False, "--polite", help="Use polite greeting"),
    greeting: Optional[str] = typer.Option(None, help="Custom greeting message")
):
    """Greet someone with customizable options."""
    message = greeting or ("Good day" if polite else "Hello")
    for i in range(count):
        typer.echo(f"{message} {name}!")

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

Prompting for Input

import typer

def create_user(
    username: str = typer.Option(..., prompt=True, help="Username for the new user"),
    password: str = typer.Option(..., prompt=True, hide_input=True, confirmation_prompt=True, help="Password for the user"),
    email: str = typer.Option(..., prompt="Email address", help="Email for the user")
):
    """Create a new user with prompted input."""
    typer.echo(f"Creating user {username} with email {email}")

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

File Parameters

import typer
from pathlib import Path

def process_file(
    input_file: Path = typer.Argument(..., exists=True, file_okay=True, dir_okay=False, help="Input file to process"),
    output_file: Path = typer.Option("output.txt", "--output", "-o", writable=True, help="Output file path"),
    config: Path = typer.Option(None, exists=True, dir_okay=False, help="Configuration file")
):
    """Process a file with optional configuration."""
    typer.echo(f"Processing {input_file} -> {output_file}")
    if config:
        typer.echo(f"Using config: {config}")

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

Numeric Ranges and Validation

import typer

def set_volume(
    level: int = typer.Option(..., min=0, max=100, clamp=True, help="Volume level (0-100)"),
    precision: float = typer.Option(1.0, min=0.1, max=10.0, help="Precision factor")
):
    """Set volume with validation."""
    typer.echo(f"Setting volume to {level} with precision {precision}")

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

Environment Variables

import typer
from typing import Optional

def connect(
    host: str = typer.Option("localhost", envvar="DB_HOST", help="Database host"),
    port: int = typer.Option(5432, envvar="DB_PORT", help="Database port"),
    username: str = typer.Option(..., envvar="DB_USER", help="Database username"),
    password: Optional[str] = typer.Option(None, envvar="DB_PASSWORD", hide_input=True, help="Database password")
):
    """Connect to database using environment variables."""
    if password is None:
        password = typer.prompt("Password", hide_input=True)
    typer.echo(f"Connecting to {host}:{port} as {username}")

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

Choices and Enums

import typer
from enum import Enum

class LogLevel(str, Enum):
    DEBUG = "debug"
    INFO = "info"
    WARNING = "warning"
    ERROR = "error"

def log_message(
    message: str = typer.Argument(..., help="Message to log"),
    level: LogLevel = typer.Option(LogLevel.INFO, help="Log level"),
    format_type: str = typer.Option("text", click_type=typer.Choice(["text", "json", "xml"]), help="Output format")
):
    """Log a message with specified level and format."""
    typer.echo(f"[{level.value.upper()}] {message} (format: {format_type})")

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

Multiple Values

import typer
from typing import List, Optional

def process_items(
    items: List[str] = typer.Argument(..., help="Items to process"),
    tags: Optional[List[str]] = typer.Option(None, "--tag", help="Tags to apply"),
    exclude: Optional[List[str]] = typer.Option(None, "--exclude", help="Items to exclude")
):
    """Process multiple items with optional tags and exclusions."""
    typer.echo(f"Processing items: {', '.join(items)}")
    if tags:
        typer.echo(f"Tags: {', '.join(tags)}")
    if exclude:
        typer.echo(f"Excluding: {', '.join(exclude)}")

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

Custom Validation

import typer
from typing import Optional

def validate_email(value: str) -> str:
    """Simple email validation."""
    if "@" not in value:
        raise typer.BadParameter("Email must contain @ symbol")
    return value

def send_email(
    to: str = typer.Option(..., parser=validate_email, help="Recipient email address"),
    subject: str = typer.Option("", help="Email subject"),
    body: Optional[str] = typer.Option(None, help="Email body")
):
    """Send an email with validation."""
    typer.echo(f"Sending email to {to}")
    typer.echo(f"Subject: {subject}")
    if body:
        typer.echo(f"Body: {body}")

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

Install with Tessl CLI

npx tessl i tessl/pypi-typer

docs

color-constants.md

core-application.md

file-handling.md

index.md

parameter-configuration.md

terminal-utilities.md

testing-support.md

tile.json