0
# Typer
1
2
Typer 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.
3
4
## Package Information
5
6
- **Package Name**: typer
7
- **Language**: Python
8
- **Installation**: `pip install typer`
9
10
## Core Imports
11
12
```python
13
import typer
14
```
15
16
Common imports for building CLI applications:
17
18
```python
19
from typer import Typer, Option, Argument
20
```
21
22
Advanced imports with type annotations:
23
24
```python
25
from typer import Typer, Option, Argument, Context
26
from typer import FileBinaryRead, FileBinaryWrite, FileText, FileTextWrite
27
```
28
29
## Basic Usage
30
31
### Simple Function CLI
32
33
```python
34
import typer
35
36
def hello(name: str):
37
"""Greet someone."""
38
print(f"Hello {name}")
39
40
if __name__ == "__main__":
41
typer.run(hello)
42
```
43
44
### Typer Application
45
46
```python
47
import typer
48
49
app = Typer()
50
51
@app.command()
52
def hello(name: str):
53
"""Greet someone."""
54
print(f"Hello {name}")
55
56
@app.command()
57
def goodbye(name: str, formal: bool = False):
58
"""Say goodbye."""
59
if formal:
60
print(f"Goodbye Ms. {name}. Have a good day.")
61
else:
62
print(f"Bye {name}!")
63
64
if __name__ == "__main__":
65
app()
66
```
67
68
## Architecture
69
70
Typer is built on Click and follows a hierarchical command structure:
71
72
- **Typer Applications**: Main application instances that can contain multiple commands and sub-applications
73
- **Commands**: Individual CLI commands registered with decorators or methods
74
- **Parameters**: Arguments and options configured through type hints and parameter functions
75
- **Context**: Shared state and configuration passed between commands
76
- **File Types**: Specialized file handling classes for different I/O operations
77
78
The library automatically converts Python function signatures into CLI interfaces, using type hints for validation and Click's robust parameter system for advanced configuration.
79
80
## Capabilities
81
82
### Core Application
83
84
The main Typer class and utilities for creating and running CLI applications, including simple function runners and URL launchers.
85
86
```python { .api }
87
class Typer:
88
def __init__(
89
self,
90
*,
91
name: Optional[str] = None,
92
cls: Optional[Type] = None,
93
invoke_without_command: bool = False,
94
no_args_is_help: bool = False,
95
subcommand_metavar: Optional[str] = None,
96
chain: bool = False,
97
result_callback: Optional[Callable[..., Any]] = None,
98
context_settings: Optional[Dict[Any, Any]] = None,
99
callback: Optional[Callable[..., Any]] = None,
100
help: Optional[str] = None,
101
epilog: Optional[str] = None,
102
short_help: Optional[str] = None,
103
options_metavar: str = "[OPTIONS]",
104
add_help_option: bool = True,
105
hidden: bool = False,
106
deprecated: bool = False,
107
add_completion: bool = True,
108
rich_markup_mode: str = "rich",
109
rich_help_panel: Optional[str] = None,
110
pretty_exceptions_enable: bool = True,
111
pretty_exceptions_show_locals: bool = True,
112
pretty_exceptions_short: bool = True,
113
): ...
114
115
def command(self, name: Optional[str] = None, **kwargs): ...
116
def callback(self, **kwargs): ...
117
def add_typer(self, typer_instance: "Typer", **kwargs): ...
118
def __call__(self, *args, **kwargs): ...
119
120
def run(function) -> None: ...
121
def launch(url: str, wait: bool = False, locate: bool = False) -> int: ...
122
```
123
124
[Core Application](./core-application.md)
125
126
### Parameter Configuration
127
128
Functions for configuring command arguments and options with type validation, help text, and advanced input handling.
129
130
```python { .api }
131
def Option(
132
default = ...,
133
*param_decls: str,
134
help: Optional[str] = None,
135
show_default: Union[bool, str] = True,
136
prompt: Union[bool, str] = False,
137
confirmation_prompt: bool = False,
138
hide_input: bool = False,
139
**kwargs
140
): ...
141
142
def Argument(
143
default = ...,
144
*,
145
help: Optional[str] = None,
146
show_default: Union[bool, str] = True,
147
**kwargs
148
): ...
149
```
150
151
[Parameter Configuration](./parameter-configuration.md)
152
153
### File Handling
154
155
Specialized file type classes for handling different types of file I/O operations in CLI applications.
156
157
```python { .api }
158
class FileText(io.TextIOWrapper): ...
159
class FileTextWrite(FileText): ...
160
class FileBinaryRead(io.BufferedReader): ...
161
class FileBinaryWrite(io.BufferedWriter): ...
162
```
163
164
[File Handling](./file-handling.md)
165
166
### Testing Support
167
168
Testing utilities for CLI applications, including a specialized test runner that works with Typer applications.
169
170
```python { .api }
171
class CliRunner:
172
def invoke(
173
self,
174
app: Typer,
175
args: Optional[Union[str, Sequence[str]]] = None,
176
input: Optional[Union[bytes, str, IO[Any]]] = None,
177
**kwargs
178
) -> Result: ...
179
```
180
181
[Testing Support](./testing-support.md)
182
183
### Terminal Utilities
184
185
Re-exported Click functions for terminal interaction, styling, and user input/output operations.
186
187
```python { .api }
188
def echo(message: Optional[str] = None, **kwargs): ...
189
def secho(message: Optional[str] = None, **kwargs): ...
190
def style(text: str, **kwargs) -> str: ...
191
def prompt(text: str, **kwargs): ...
192
def confirm(text: str, **kwargs) -> bool: ...
193
def clear(): ...
194
def pause(info: str = "Press any key to continue..."): ...
195
```
196
197
[Terminal Utilities](./terminal-utilities.md)
198
199
### Color Constants
200
201
Named color constants for use with terminal styling functions.
202
203
```python { .api }
204
BLACK: str = "black"
205
RED: str = "red"
206
GREEN: str = "green"
207
YELLOW: str = "yellow"
208
BLUE: str = "blue"
209
MAGENTA: str = "magenta"
210
CYAN: str = "cyan"
211
WHITE: str = "white"
212
RESET: str = "reset"
213
214
BRIGHT_BLACK: str = "bright_black"
215
BRIGHT_RED: str = "bright_red"
216
BRIGHT_GREEN: str = "bright_green"
217
BRIGHT_YELLOW: str = "bright_yellow"
218
BRIGHT_BLUE: str = "bright_blue"
219
BRIGHT_MAGENTA: str = "bright_magenta"
220
BRIGHT_CYAN: str = "bright_cyan"
221
BRIGHT_WHITE: str = "bright_white"
222
```
223
224
[Color Constants](./color-constants.md)
225
226
## Types
227
228
Core type definitions used throughout the Typer API.
229
230
```python { .api }
231
class Context(click.Context):
232
"""Click context for accessing command state and configuration."""
233
234
class CallbackParam(click.Parameter):
235
"""Parameter class for callback functions."""
236
237
# Type definitions for common types used in the API
238
from typing import Any, Callable, Dict, List, Optional, Type, Union
239
240
# Sentinel values and utility functions
241
Required = ... # Sentinel value for required parameters
242
243
def Default(value: Any) -> Any:
244
"""
245
Mark a parameter as having a default value.
246
247
Args:
248
value: The default value to use
249
250
Returns:
251
The default value wrapped for Typer's internal use
252
"""
253
```
254
255
## Exceptions
256
257
Exception classes for error handling in CLI applications.
258
259
```python { .api }
260
class Abort(click.ClickException):
261
"""Exception to abort command execution."""
262
263
class BadParameter(click.ClickException):
264
"""Exception for invalid parameter values."""
265
266
class Exit(click.ClickException):
267
"""Exception to exit the program with a specific code."""
268
```