Building Python CLI Applications with Typer
Typer revolutionizes Python command-line interface development by leveraging type hints for automatic argument parsing and help ganeration. This modern library simplifies CLI creation while maintainnig robust functionality.
Core Functionality
Typer uses Python's native type annotations to define command parameters:
import typer
app = typer.Typer()
@app.command()
def greet(username: str):
"""Display personalized greeting"""
print(f"Welcome, {username}!")
This basic example demonstrates a greeting command that accepts a string parameter. The type hint automatically configures the argument parser.
Parameter Handling
Typer supports various parameter types with built-in validation:
@app.command()
def calculate(
base: float,
modifier: int,
operation: str = typer.Option("add", help="Math operation")
):
"""Perform arithmetic operations"""
if operation == "add":
result = base + modifier
elif operation == "subtract":
result = base - modifier
else:
raise ValueError("Invalid operation")
print(f"Result: {result}")
Error Management
The library provides clean error handling mechanisms:
@app.command()
def file_operation(
path: str,
force: bool = typer.Option(False, help="Override safety checks")
):
"""Handle file operations"""
if not force and not path.exists():
print("Use --force to override checks")
return
# Proceed with operation
Advanced Features
For complex applications, Typer supports subcommands and external integrations:
@app.command()
def db_query(query: str):
"""Execute database operations"""
# Database integration code
print(f"Executed: {query}")