📝 Add reference (code API) docs (#1504)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Sofie Van Landeghem · committed by GitHub · parent 1db87e0 · Browse files · 12 files·+2670 added−176 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Trailers
- Co-authored-by: pre-commit-ci-lite[bot] <117423508+pre-commit-ci-lite[bot]@users.noreply.github.com>
- Co-authored-by: Sebastián Ramírez <tiangolo@gmail.com>
Diff stats
12 files+2670 added−176 removed
- other:+2670 added−176 removed
Provenance
- Commit
2d529b2- Tree
e54474e- Author
Sofie Van Landeghem <svlandeg@users.noreply.github.com>- Committer
GitHub <noreply@github.com>- Parent
1db87e0
12 files changed+2670 added−176 removed
added:docs/reference/context.md+38 added
1234567891011121314151617181920212223242526272829303132333435363738# Context
When you create a Typer application it uses Click underneath.And every Click application has a special object called a [`Context`](https://click.palletsprojects.com/en/stable/api/#click.Context) that is normally hidden.But you can access the context by declaring a function parameter of type `typer.Context`.
The same way you can access the context by declaring a function parameter with its value,you can declare another function parameter with type `typer.CallbackParam` to get the specific Click [`Parameter`](https://click.palletsprojects.com/en/stable/api/#click.Parameter) object.
```pythonfrom typing import Annotated
import typer
app = typer.Typer()
def name_callback(ctx: typer.Context, param: typer.CallbackParam, value: str): if ctx.resilient_parsing: return print(f"Validating param: {param.name}") if value != "Rick": raise typer.BadParameter("Only Rick is allowed") return value
@app.command()def main(name: Annotated[str | None, typer.Option(callback=name_callback)] = None): print(f"Hello {name}")
if __name__ == "__main__": app()```
::: typer.Context
::: typer.CallbackParamadded:docs/reference/file_objects.md+18 added
123456789101112131415161718# File objects
When you want to declare some types of files, you can use `Path`.However, in some cases you may need to have access to a file-like object, and then you can use these [special File types](https://typer.tiangolo.com/tutorial/parameter-types/file/).
These objects can be imported from `typer` directly:
```pythonfrom typer import FileBinaryRead, FileBinaryWrite, FileText, FileTextWrite```
::: typer.FileText
::: typer.FileTextWrite
::: typer.FileBinaryRead
::: typer.FileBinaryWriteadded:docs/reference/index.md+7 added
1234567# Reference
Here's the reference or code API, the classes, functions, parameters, attributes, andall the Typer parts you can use in your applications.
If you want to **learn Typer** you are much better off reading the[Typer Tutorial](https://typer.tiangolo.com/tutorial/).added:docs/reference/parameters.md+31 added
12345678910111213141516171819202122232425262728293031# Parameters
Parameters to our command line interface may be both [CLI Options](https://typer.tiangolo.com/tutorial/options/) and [CLI Arguments](https://typer.tiangolo.com/tutorial/arguments/):
```pythonfrom typing import Annotatedimport typer
app = typer.Typer()
@app.command()def register( user: Annotated[str, typer.Argument()], age: Annotated[int, typer.Option(min=18)], score: Annotated[float, typer.Option(max=100)] = 0,): print(f"User is {user}") print(f"--age is {age}") print(f"--score is {score}")
if __name__ == "__main__": app()```
::: typer.Argument options: show_overloads: false
::: typer.Option options: show_overloads: falseadded:docs/reference/run_launch.md+11 added
1234567891011# `run` and `launch`
These two functions can be imported from `typer` directly:
```pythonfrom typer import launch, run```
::: typer.run
::: typer.launchadded:docs/reference/typer.md+16 added
12345678910111213141516# `Typer` class
Here's the reference information for the `Typer` class, with all its parameters, attributes and methods.
You can import the `Typer` class directly from `typer`:
```pythonfrom typer import Typer```
::: typer.Typer options: members: - callback - command - add_typermodified:typer/main.py+949 added-86 removed
10 unmodified lines11 from functools import update_wrapper12 from pathlib import Path13 from traceback import FrameSummary, StackSummary14 from types import TracebackType15-from typing import Any, Callable, Optional, Union15+from typing import Annotated, Any, Callable, Optional, Union16 from uuid import UUID17 18 import click19+from annotated_doc import Doc20 from typer._types import TyperChoice21 22 from ._typing import get_args, get_origin, is_literal_type, is_union, literal_values23 from .completion import get_completion_inspect_parameters90 unmodified lines114 return click_install_param, click_show_param115 116 117 class Typer:118+ """119+ `Typer` main class, the main entrypoint to use Typer.120+121+ Read more in the122+ [Typer docs for First Steps](https://typer.tiangolo.com/tutorial/typer-app/).123+124+ ## Example125+126+ ```python127+ import typer128+129+ app = typer.Typer()130+ ```131+ """132+133 def __init__(134 self,135 *,120- name: Optional[str] = Default(None),121- cls: Optional[type[TyperGroup]] = Default(None),122- invoke_without_command: bool = Default(False),123- no_args_is_help: bool = Default(False),124- subcommand_metavar: Optional[str] = Default(None),125- chain: bool = Default(False),126- result_callback: Optional[Callable[..., Any]] = Default(None),136+ name: Annotated[137+ Optional[str],138+ Doc(139+ """140+ The name of this application.141+ Mostly used to set the name for [subcommands](https://typer.tiangolo.com/tutorial/subcommands/), in which case it can be overridden by `add_typer(name=...)`.142+143+ **Example**144+145+ ```python146+ import typer147+148+ app = typer.Typer(name="users")149+ ```150+ """151+ ),152+ ] = Default(None),153+ cls: Annotated[154+ Optional[type[TyperGroup]],155+ Doc(156+ """157+ The class of this app. Mainly used when [using the Click library underneath](https://typer.tiangolo.com/tutorial/using-click/). Can usually be left at the default value `None`.158+ Otherwise, should be a subtype of `TyperGroup`.159+160+ **Example**161+162+ ```python163+ import typer164+165+ app = typer.Typer(cls=TyperGroup)166+ ```167+ """168+ ),169+ ] = Default(None),170+ invoke_without_command: Annotated[171+ bool,172+ Doc(173+ """174+ By setting this to `True`, you can make sure a callback is executed even when no subcommand is provided.175+176+ **Example**177+178+ ```python179+ import typer180+181+ app = typer.Typer(invoke_without_command=True)182+ ```183+ """184+ ),185+ ] = Default(False),186+ no_args_is_help: Annotated[187+ bool,188+ Doc(189+ """190+ If this is set to `True`, running a command without any arguments will automatically show the help page.191+192+ **Example**193+194+ ```python195+ import typer196+197+ app = typer.Typer(no_args_is_help=True)198+ ```199+ """200+ ),201+ ] = Default(False),202+ subcommand_metavar: Annotated[203+ Optional[str],204+ Doc(205+ """206+ **Note**: you probably shouldn't use this parameter, it is inherited207+ from Click and supported for compatibility.208+209+ ---210+211+ How to represent the subcommand argument in help.212+ """213+ ),214+ ] = Default(None),215+ chain: Annotated[216+ bool,217+ Doc(218+ """219+ **Note**: you probably shouldn't use this parameter, it is inherited220+ from Click and supported for compatibility.221+222+ ---223+224+ Allow passing more than one subcommand argument.225+ """226+ ),227+ ] = Default(False),228+ result_callback: Annotated[229+ Optional[Callable[..., Any]],230+ Doc(231+ """232+ **Note**: you probably shouldn't use this parameter, it is inherited233+ from Click and supported for compatibility.234+235+ ---236+237+ A function to call after the group's and subcommand's callbacks.238+ """239+ ),240+ ] = Default(None),241 # Command128- context_settings: Optional[dict[Any, Any]] = Default(None),129- callback: Optional[Callable[..., Any]] = Default(None),130- help: Optional[str] = Default(None),131- epilog: Optional[str] = Default(None),132- short_help: Optional[str] = Default(None),133- options_metavar: str = Default("[OPTIONS]"),134- add_help_option: bool = Default(True),135- hidden: bool = Default(False),136- deprecated: bool = Default(False),137- add_completion: bool = True,242+ context_settings: Annotated[243+ Optional[dict[Any, Any]],244+ Doc(245+ """246+ Pass configurations for the [context](https://typer.tiangolo.com/tutorial/commands/context/).247+ Available configurations can be found in the docs for Click's `Context` [here](https://click.palletsprojects.com/en/stable/api/#context).248+249+ **Example**250+251+ ```python252+ import typer253+254+ app = typer.Typer(context_settings={"help_option_names": ["-h", "--help"]})255+ ```256+ """257+ ),258+ ] = Default(None),259+ callback: Annotated[260+ Optional[Callable[..., Any]],261+ Doc(262+ """263+ Add a callback to the main Typer app. Can be overridden with `@app.callback()`.264+ See [the tutorial about callbacks](https://typer.tiangolo.com/tutorial/commands/callback/) for more details.265+266+ **Example**267+268+ ```python269+ import typer270+271+ def callback():272+ print("Running a command")273+274+ app = typer.Typer(callback=callback)275+ ```276+ """277+ ),278+ ] = Default(None),279+ help: Annotated[280+ Optional[str],281+ Doc(282+ """283+ Help text for the main Typer app.284+ See [the tutorial about name and help](https://typer.tiangolo.com/tutorial/subcommands/name-and-help) for different ways of setting a command's help,285+ and which one takes priority.286+287+ **Example**288+289+ ```python290+ import typer291+292+ app = typer.Typer(help="Some help.")293+ ```294+ """295+ ),296+ ] = Default(None),297+ epilog: Annotated[298+ Optional[str],299+ Doc(300+ """301+ Text that will be printed right after the help text.302+303+ **Example**304+305+ ```python306+ import typer307+308+ app = typer.Typer(epilog="May the force be with you")309+ ```310+ """311+ ),312+ ] = Default(None),313+ short_help: Annotated[314+ Optional[str],315+ Doc(316+ """317+ A shortened version of the help text that can be used e.g. in the help table listing subcommands.318+ When not defined, the normal `help` text will be used instead.319+320+ **Example**321+322+ ```python323+ import typer324+325+ app = typer.Typer(help="A lot of explanation about user management", short_help="user management")326+ ```327+ """328+ ),329+ ] = Default(None),330+ options_metavar: Annotated[331+ str,332+ Doc(333+ """334+ In the example usage string of the help text for a command, the default placeholder for various arguments is `[OPTIONS]`.335+ Set `options_metavar` to change this into a different string.336+337+ **Example**338+339+ ```python340+ import typer341+342+ app = typer.Typer(options_metavar="[OPTS]")343+ ```344+ """345+ ),346+ ] = Default("[OPTIONS]"),347+ add_help_option: Annotated[348+ bool,349+ Doc(350+ """351+ **Note**: you probably shouldn't use this parameter, it is inherited352+ from Click and supported for compatibility.353+354+ ---355+356+ By default each command registers a `--help` option. This can be disabled by this parameter.357+ """358+ ),359+ ] = Default(True),360+ hidden: Annotated[361+ bool,362+ Doc(363+ """364+ Hide this command from help outputs. `False` by default.365+366+ **Example**367+368+ ```python369+ import typer370+371+ app = typer.Typer(hidden=True)372+ ```373+ """374+ ),375+ ] = Default(False),376+ deprecated: Annotated[377+ bool,378+ Doc(379+ """380+ Mark this command as being deprecated in the help text. `False` by default.381+382+ **Example**383+384+ ```python385+ import typer386+387+ app = typer.Typer(deprecated=True)388+ ```389+ """390+ ),391+ ] = Default(False),392+ add_completion: Annotated[393+ bool,394+ Doc(395+ """396+ Toggle whether or not to add the `--install-completion` and `--show-completion` options to the app.397+ Set to `True` by default.398+399+ **Example**400+401+ ```python402+ import typer403+404+ app = typer.Typer(add_completion=False)405+ ```406+ """407+ ),408+ ] = True,409 # Rich settings139- rich_markup_mode: MarkupMode = DEFAULT_MARKUP_MODE,140- rich_help_panel: Union[str, None] = Default(None),141- suggest_commands: bool = True,142- pretty_exceptions_enable: bool = True,143- pretty_exceptions_show_locals: bool = True,144- pretty_exceptions_short: bool = True,410+ rich_markup_mode: Annotated[411+ MarkupMode,412+ Doc(413+ """414+ Enable markup text if you have Rich installed. This can be set to `"markdown"`, `"rich"`, or `None`.415+ By default, `rich_markup_mode` is `None` if Rich is not installed, and `"rich"` if it is installed.416+ See [the tutorial on help formatting](https://typer.tiangolo.com/tutorial/commands/help/#rich-markdown-and-markup) for more information.417+418+ **Example**419+420+ ```python421+ import typer422+423+ app = typer.Typer(rich_markup_mode="rich")424+ ```425+ """426+ ),427+ ] = DEFAULT_MARKUP_MODE,428+ rich_help_panel: Annotated[429+ Union[str, None],430+ Doc(431+ """432+ Set the panel name of the command when the help is printed with Rich.433+434+ **Example**435+436+ ```python437+ import typer438+439+ app = typer.Typer(rich_help_panel="Utils and Configs")440+ ```441+ """442+ ),443+ ] = Default(None),444+ suggest_commands: Annotated[445+ bool,446+ Doc(447+ """448+ As of version 0.20.0, Typer provides [support for mistyped command names](https://typer.tiangolo.com/tutorial/commands/help/#suggest-commands) by printing helpful suggestions.449+ You can turn this setting off with `suggest_commands`:450+451+ **Example**452+453+ ```python454+ import typer455+456+ app = typer.Typer(suggest_commands=False)457+ ```458+ """459+ ),460+ ] = True,461+ pretty_exceptions_enable: Annotated[462+ bool,463+ Doc(464+ """465+ If you want to disable [pretty exceptions with Rich](https://typer.tiangolo.com/tutorial/exceptions/#exceptions-with-rich),466+ you can set `pretty_exceptions_enable` to `False`. When doing so, you will see the usual standard exception trace.467+468+ **Example**469+470+ ```python471+ import typer472+473+ app = typer.Typer(pretty_exceptions_enable=False)474+ ```475+ """476+ ),477+ ] = True,478+ pretty_exceptions_show_locals: Annotated[479+ bool,480+ Doc(481+ """482+ If Rich is installed, [error messages](https://typer.tiangolo.com/tutorial/exceptions/#exceptions-and-errors)483+ will be nicely printed and include the values of local variables for easy debugging.484+ However, if such a variable contains delicate information, you should consider setting `pretty_exceptions_show_locals` to `False`485+ to enhance security.486+487+ **Example**488+489+ ```python490+ import typer491+492+ app = typer.Typer(pretty_exceptions_show_locals=False)493+ ```494+ """495+ ),496+ ] = True,497+ pretty_exceptions_short: Annotated[498+ bool,499+ Doc(500+ """501+ By default, [pretty exceptions formatted with Rich](https://typer.tiangolo.com/tutorial/exceptions/#exceptions-with-rich) hide the long stack trace.502+ If you want to show the full trace instead, you can set the parameter `pretty_exceptions_short` to `False`:503+504+ **Example**505+506+ ```python507+ import typer508+509+ app = typer.Typer(pretty_exceptions_short=False)510+ ```511+ """512+ ),513+ ] = True,514 ):515 self._add_completion = add_completion516 self.rich_markup_mode: MarkupMode = rich_markup_mode517 self.rich_help_panel = rich_help_panel25 unmodified lines543 544 def callback(545 self,546 *,178- cls: Optional[type[TyperGroup]] = Default(None),179- invoke_without_command: bool = Default(False),180- no_args_is_help: bool = Default(False),181- subcommand_metavar: Optional[str] = Default(None),182- chain: bool = Default(False),183- result_callback: Optional[Callable[..., Any]] = Default(None),547+ cls: Annotated[548+ Optional[type[TyperGroup]],549+ Doc(550+ """551+ The class of this app. Mainly used when [using the Click library underneath](https://typer.tiangolo.com/tutorial/using-click/). Can usually be left at the default value `None`.552+ Otherwise, should be a subtype of `TyperGroup`.553+ """554+ ),555+ ] = Default(None),556+ invoke_without_command: Annotated[557+ bool,558+ Doc(559+ """560+ By setting this to `True`, you can make sure a callback is executed even when no subcommand is provided.561+ """562+ ),563+ ] = Default(False),564+ no_args_is_help: Annotated[565+ bool,566+ Doc(567+ """568+ If this is set to `True`, running a command without any arguments will automatically show the help page.569+ """570+ ),571+ ] = Default(False),572+ subcommand_metavar: Annotated[573+ Optional[str],574+ Doc(575+ """576+ **Note**: you probably shouldn't use this parameter, it is inherited577+ from Click and supported for compatibility.578+579+ ---580+581+ How to represent the subcommand argument in help.582+ """583+ ),584+ ] = Default(None),585+ chain: Annotated[586+ bool,587+ Doc(588+ """589+ **Note**: you probably shouldn't use this parameter, it is inherited590+ from Click and supported for compatibility.591+592+ ---593+594+ Allow passing more than one subcommand argument.595+ """596+ ),597+ ] = Default(False),598+ result_callback: Annotated[599+ Optional[Callable[..., Any]],600+ Doc(601+ """602+ **Note**: you probably shouldn't use this parameter, it is inherited603+ from Click and supported for compatibility.604+605+ ---606+607+ A function to call after the group's and subcommand's callbacks.608+ """609+ ),610+ ] = Default(None),611 # Command185- context_settings: Optional[dict[Any, Any]] = Default(None),186- help: Optional[str] = Default(None),187- epilog: Optional[str] = Default(None),188- short_help: Optional[str] = Default(None),189- options_metavar: Optional[str] = Default(None),190- add_help_option: bool = Default(True),191- hidden: bool = Default(False),192- deprecated: bool = Default(False),612+ context_settings: Annotated[613+ Optional[dict[Any, Any]],614+ Doc(615+ """616+ Pass configurations for the [context](https://typer.tiangolo.com/tutorial/commands/context/).617+ Available configurations can be found in the docs for Click's `Context` [here](https://click.palletsprojects.com/en/stable/api/#context).618+ """619+ ),620+ ] = Default(None),621+ help: Annotated[622+ Optional[str],623+ Doc(624+ """625+ Help text for the command.626+ See [the tutorial about name and help](https://typer.tiangolo.com/tutorial/subcommands/name-and-help) for different ways of setting a command's help,627+ and which one takes priority.628+ """629+ ),630+ ] = Default(None),631+ epilog: Annotated[632+ Optional[str],633+ Doc(634+ """635+ Text that will be printed right after the help text.636+ """637+ ),638+ ] = Default(None),639+ short_help: Annotated[640+ Optional[str],641+ Doc(642+ """643+ A shortened version of the help text that can be used e.g. in the help table listing subcommands.644+ When not defined, the normal `help` text will be used instead.645+ """646+ ),647+ ] = Default(None),648+ options_metavar: Annotated[649+ Optional[str],650+ Doc(651+ """652+ In the example usage string of the help text for a command, the default placeholder for various arguments is `[OPTIONS]`.653+ Set `options_metavar` to change this into a different string. When `None`, the default value will be used.654+ """655+ ),656+ ] = Default(None),657+ add_help_option: Annotated[658+ bool,659+ Doc(660+ """661+ **Note**: you probably shouldn't use this parameter, it is inherited662+ from Click and supported for compatibility.663+664+ ---665+666+ By default each command registers a `--help` option. This can be disabled by this parameter.667+ """668+ ),669+ ] = Default(True),670+ hidden: Annotated[671+ bool,672+ Doc(673+ """674+ Hide this command from help outputs. `False` by default.675+ """676+ ),677+ ] = Default(False),678+ deprecated: Annotated[679+ bool,680+ Doc(681+ """682+ Mark this command as deprecated in the help text. `False` by default.683+ """684+ ),685+ ] = Default(False),686 # Rich settings194- rich_help_panel: Union[str, None] = Default(None),687+ rich_help_panel: Annotated[688+ Union[str, None],689+ Doc(690+ """691+ Set the panel name of the command when the help is printed with Rich.692+ """693+ ),694+ ] = Default(None),695 ) -> Callable[[CommandFunctionType], CommandFunctionType]:696+ """697+ Using the decorator `@app.callback`, you can declare the CLI parameters for the main CLI application.698+699+ Read more in the700+ [Typer docs for Callbacks](https://typer.tiangolo.com/tutorial/commands/callback/).701+702+ ## Example703+704+ ```python705+ import typer706+707+ app = typer.Typer()708+ state = {"verbose": False}709+710+ @app.callback()711+ def main(verbose: bool = False):712+ if verbose:713+ print("Will write verbose output")714+ state["verbose"] = True715+716+ @app.command()717+ def delete(username: str):718+ # define subcommand719+ ...720+ ```721+ """722+723 def decorator(f: CommandFunctionType) -> CommandFunctionType:724 self.registered_callback = TyperInfo(725 cls=cls,726 invoke_without_command=invoke_without_command,19 unmodified lines746 return decorator747 748 def command(749 self,223- name: Optional[str] = None,750+ name: Annotated[751+ Optional[str],752+ Doc(753+ """754+ The name of this command.755+ """756+ ),757+ ] = None,758 *,225- cls: Optional[type[TyperCommand]] = None,226- context_settings: Optional[dict[Any, Any]] = None,227- help: Optional[str] = None,228- epilog: Optional[str] = None,229- short_help: Optional[str] = None,230- options_metavar: Optional[str] = None,231- add_help_option: bool = True,232- no_args_is_help: bool = False,233- hidden: bool = False,234- deprecated: bool = False,759+ cls: Annotated[760+ Optional[type[TyperCommand]],761+ Doc(762+ """763+ The class of this command. Mainly used when [using the Click library underneath](https://typer.tiangolo.com/tutorial/using-click/). Can usually be left at the default value `None`.764+ Otherwise, should be a subtype of `TyperCommand`.765+ """766+ ),767+ ] = None,768+ context_settings: Annotated[769+ Optional[dict[Any, Any]],770+ Doc(771+ """772+ Pass configurations for the [context](https://typer.tiangolo.com/tutorial/commands/context/).773+ Available configurations can be found in the docs for Click's `Context` [here](https://click.palletsprojects.com/en/stable/api/#context).774+ """775+ ),776+ ] = None,777+ help: Annotated[778+ Optional[str],779+ Doc(780+ """781+ Help text for the command.782+ See [the tutorial about name and help](https://typer.tiangolo.com/tutorial/subcommands/name-and-help) for different ways of setting a command's help,783+ and which one takes priority.784+ """785+ ),786+ ] = None,787+ epilog: Annotated[788+ Optional[str],789+ Doc(790+ """791+ Text that will be printed right after the help text.792+ """793+ ),794+ ] = None,795+ short_help: Annotated[796+ Optional[str],797+ Doc(798+ """799+ A shortened version of the help text that can be used e.g. in the help table listing subcommands.800+ When not defined, the normal `help` text will be used instead.801+ """802+ ),803+ ] = None,804+ options_metavar: Annotated[805+ Optional[str],806+ Doc(807+ """808+ In the example usage string of the help text for a command, the default placeholder for various arguments is `[OPTIONS]`.809+ Set `options_metavar` to change this into a different string. When `None`, the default value will be used.810+ """811+ ),812+ ] = Default(None),813+ add_help_option: Annotated[814+ bool,815+ Doc(816+ """817+ **Note**: you probably shouldn't use this parameter, it is inherited818+ from Click and supported for compatibility.819+820+ ---821+822+ By default each command registers a `--help` option. This can be disabled by this parameter.823+ """824+ ),825+ ] = True,826+ no_args_is_help: Annotated[827+ bool,828+ Doc(829+ """830+ If this is set to `True`, running a command without any arguments will automatically show the help page.831+ """832+ ),833+ ] = False,834+ hidden: Annotated[835+ bool,836+ Doc(837+ """838+ Hide this command from help outputs. `False` by default.839+ """840+ ),841+ ] = False,842+ deprecated: Annotated[843+ bool,844+ Doc(845+ """846+ Mark this command as deprecated in the help outputs. `False` by default.847+ """848+ ),849+ ] = False,850 # Rich settings236- rich_help_panel: Union[str, None] = Default(None),851+ rich_help_panel: Annotated[852+ Union[str, None],853+ Doc(854+ """855+ Set the panel name of the command when the help is printed with Rich.856+ """857+ ),858+ ] = Default(None),859 ) -> Callable[[CommandFunctionType], CommandFunctionType]:860+ """861+ Using the decorator `@app.command`, you can define a subcommand of the previously defined Typer app.862+863+ Read more in the864+ [Typer docs for Commands](https://typer.tiangolo.com/tutorial/commands/).865+866+ ## Example867+868+ ```python869+ import typer870+871+ app = typer.Typer()872+873+ @app.command()874+ def create():875+ print("Creating user: Hiro Hamada")876+877+ @app.command()878+ def delete():879+ print("Deleting user: Hiro Hamada")880+ ```881+ """882 if cls is None:883 cls = TyperCommand884 885 def decorator(f: CommandFunctionType) -> CommandFunctionType:24 unmodified lines910 def add_typer(911 self,912 typer_instance: "Typer",913 *,270- name: Optional[str] = Default(None),271- cls: Optional[type[TyperGroup]] = Default(None),272- invoke_without_command: bool = Default(False),273- no_args_is_help: bool = Default(False),274- subcommand_metavar: Optional[str] = Default(None),275- chain: bool = Default(False),276- result_callback: Optional[Callable[..., Any]] = Default(None),914+ name: Annotated[915+ Optional[str],916+ Doc(917+ """918+ The name of this subcommand.919+ See [the tutorial about name and help](https://typer.tiangolo.com/tutorial/subcommands/name-and-help) for different ways of setting a command's name,920+ and which one takes priority.921+ """922+ ),923+ ] = Default(None),924+ cls: Annotated[925+ Optional[type[TyperGroup]],926+ Doc(927+ """928+ The class of this subcommand. Mainly used when [using the Click library underneath](https://typer.tiangolo.com/tutorial/using-click/). Can usually be left at the default value `None`.929+ Otherwise, should be a subtype of `TyperGroup`.930+ """931+ ),932+ ] = Default(None),933+ invoke_without_command: Annotated[934+ bool,935+ Doc(936+ """937+ By setting this to `True`, you can make sure a callback is executed even when no subcommand is provided.938+ """939+ ),940+ ] = Default(False),941+ no_args_is_help: Annotated[942+ bool,943+ Doc(944+ """945+ If this is set to `True`, running a command without any arguments will automatically show the help page.946+ """947+ ),948+ ] = Default(False),949+ subcommand_metavar: Annotated[950+ Optional[str],951+ Doc(952+ """953+ **Note**: you probably shouldn't use this parameter, it is inherited954+ from Click and supported for compatibility.955+956+ ---957+958+ How to represent the subcommand argument in help.959+ """960+ ),961+ ] = Default(None),962+ chain: Annotated[963+ bool,964+ Doc(965+ """966+ **Note**: you probably shouldn't use this parameter, it is inherited967+ from Click and supported for compatibility.968+969+ ---970+971+ Allow passing more than one subcommand argument.972+ """973+ ),974+ ] = Default(False),975+ result_callback: Annotated[976+ Optional[Callable[..., Any]],977+ Doc(978+ """979+ **Note**: you probably shouldn't use this parameter, it is inherited980+ from Click and supported for compatibility.981+982+ ---983+984+ A function to call after the group's and subcommand's callbacks.985+ """986+ ),987+ ] = Default(None),988 # Command278- context_settings: Optional[dict[Any, Any]] = Default(None),279- callback: Optional[Callable[..., Any]] = Default(None),280- help: Optional[str] = Default(None),281- epilog: Optional[str] = Default(None),282- short_help: Optional[str] = Default(None),283- options_metavar: Optional[str] = Default(None),284- add_help_option: bool = Default(True),285- hidden: bool = Default(False),286- deprecated: bool = Default(False),989+ context_settings: Annotated[990+ Optional[dict[Any, Any]],991+ Doc(992+ """993+ Pass configurations for the [context](https://typer.tiangolo.com/tutorial/commands/context/).994+ Available configurations can be found in the docs for Click's `Context` [here](https://click.palletsprojects.com/en/stable/api/#context).995+ """996+ ),997+ ] = Default(None),998+ callback: Annotated[999+ Optional[Callable[..., Any]],1000+ Doc(1001+ """1002+ Add a callback to this app.1003+ See [the tutorial about callbacks](https://typer.tiangolo.com/tutorial/commands/callback/) for more details.1004+ """1005+ ),1006+ ] = Default(None),1007+ help: Annotated[1008+ Optional[str],1009+ Doc(1010+ """1011+ Help text for the subcommand.1012+ See [the tutorial about name and help](https://typer.tiangolo.com/tutorial/subcommands/name-and-help) for different ways of setting a command's help,1013+ and which one takes priority.1014+ """1015+ ),1016+ ] = Default(None),1017+ epilog: Annotated[1018+ Optional[str],1019+ Doc(1020+ """1021+ Text that will be printed right after the help text.1022+ """1023+ ),1024+ ] = Default(None),1025+ short_help: Annotated[1026+ Optional[str],1027+ Doc(1028+ """1029+ A shortened version of the help text that can be used e.g. in the help table listing subcommands.1030+ When not defined, the normal `help` text will be used instead.1031+ """1032+ ),1033+ ] = Default(None),1034+ options_metavar: Annotated[1035+ Optional[str],1036+ Doc(1037+ """1038+ In the example usage string of the help text for a command, the default placeholder for various arguments is `[OPTIONS]`.1039+ Set `options_metavar` to change this into a different string. When `None`, the default value will be used.1040+ """1041+ ),1042+ ] = Default(None),1043+ add_help_option: Annotated[1044+ bool,1045+ Doc(1046+ """1047+ **Note**: you probably shouldn't use this parameter, it is inherited1048+ from Click and supported for compatibility.1049+1050+ ---1051+1052+ By default each command registers a `--help` option. This can be disabled by this parameter.1053+ """1054+ ),1055+ ] = Default(True),1056+ hidden: Annotated[1057+ bool,1058+ Doc(1059+ """1060+ Hide this command from help outputs. `False` by default.1061+ """1062+ ),1063+ ] = Default(False),1064+ deprecated: Annotated[1065+ bool,1066+ Doc(1067+ """1068+ Mark this command as deprecated in the help outputs. `False` by default.1069+ """1070+ ),1071+ ] = False,1072 # Rich settings288- rich_help_panel: Union[str, None] = Default(None),1073+ rich_help_panel: Annotated[1074+ Union[str, None],1075+ Doc(1076+ """1077+ Set the panel name of the command when the help is printed with Rich.1078+ """1079+ ),1080+ ] = Default(None),1081 ) -> None:1082+ """1083+ Add subcommands to the main app using `app.add_typer()`.1084+ Subcommands may be defined in separate modules, ensuring clean separation of code by functionality.1085+1086+ Read more in the1087+ [Typer docs for SubCommands](https://typer.tiangolo.com/tutorial/subcommands/add-typer/).1088+1089+ ## Example1090+1091+ ```python1092+ import typer1093+1094+ from .add import app as add_app1095+ from .delete import app as delete_app1096+1097+ app = typer.Typer()1098+1099+ app.add_typer(add_app)1100+ app.add_typer(delete_app)1101+ ```1102+ """1103 self.registered_groups.append(1104 TyperInfo(1105 typer_instance,1106 name=name,783 unmodified lines1890 update_wrapper(wrapper, callback)1891 return wrapper1892 1893 1081-def run(function: Callable[..., Any]) -> None:1894+def run(1895+ function: Annotated[1896+ Callable[..., Any],1897+ Doc(1898+ """1899+ The function that should power this CLI application.1900+ """1901+ ),1902+ ],1903+) -> None:1904+ """1905+ This function converts a given function to a CLI application with `Typer()` and executes it.1906+1907+ ## Example1908+1909+ ```python1910+ import typer1911+1912+ def main(name: str):1913+ print(f"Hello {name}")1914+1915+ if __name__ == "__main__":1916+ typer.run(main)1917+ ```1918+ """1919 app = Typer(add_completion=False)1920 app.command()(function)1921 app()1922 8 unmodified lines1931 1932 return "BSD" in platform.system()1933 1934 1098-def launch(url: str, wait: bool = False, locate: bool = False) -> int:1099- """This function launches the given URL (or filename) in the default1935+def launch(1936+ url: Annotated[1937+ str,1938+ Doc(1939+ """1940+ URL or filename of the thing to launch.1941+ """1942+ ),1943+ ],1944+ wait: Annotated[1945+ bool,1946+ Doc(1947+ """1948+ Wait for the program to exit before returning. This only works if the launched program blocks.1949+ In particular, `xdg-open` on Linux does not block.1950+ """1951+ ),1952+ ] = False,1953+ locate: Annotated[1954+ bool,1955+ Doc(1956+ """1957+ If this is set to `True`, then instead of launching the application associated with the URL, it will attempt to1958+ launch a file manager with the file located. This might have weird effects if the URL does not point to the filesystem.1959+ """1960+ ),1961+ ] = False,1962+) -> int:1963+ """1964+ This function launches the given URL (or filename) in the default1965 viewer application for this file type. If this is an executable, it1966 might launch the executable in a new session. The return value is1102- the exit code of the launched application. Usually, ``0`` indicates1967+ the exit code of the launched application. Usually, `0` indicates1968 success.1969 1970 This function handles url in different operating systems separately:1106- - On macOS (Darwin), it uses the 'open' command.1107- - On Linux and BSD, it uses 'xdg-open' if available.1108- - On Windows (and other OSes), it uses the standard webbrowser module.1971+ - On macOS (Darwin), it uses the `open` command.1972+ - On Linux and BSD, it uses `xdg-open` if available.1973+ - On Windows (and other OSes), it uses the standard webbrowser module.1974 1975 The function avoids, when possible, using the webbrowser module on Linux and macOS1976 to prevent spammy terminal messages from some browsers (e.g., Chrome).1977 1113- Examples::1978+ ## Examples1979+ ```python1980+ import typer1981 1982 typer.launch("https://typer.tiangolo.com/")1116- typer.launch("/my/downloaded/file", locate=True)1983+ ```1984 1118- :param url: URL or filename of the thing to launch.1119- :param wait: Wait for the program to exit before returning. This1120- only works if the launched program blocks. In particular,1121- ``xdg-open`` on Linux does not block.1122- :param locate: if this is set to `True` then instead of launching the1123- application associated with the URL it will attempt to1124- launch a file manager with the file located. This1125- might have weird effects if the URL does not point to1126- the filesystem.1985+ ```python1986+ import typer1987+1988+ typer.launch("/my/downloaded/file", locate=True)1989+ ```1990 """1991 1992 if url.startswith("http://") or url.startswith("https://"):1993 if _is_macos():19 unmodified linesmodified:typer/models.py+115 added
24 unmodified lines25 Required = ...26 27 28 class Context(click.Context):29+ """30+ The [`Context`](https://click.palletsprojects.com/en/stable/api/#click.Context) has some additional data about the current execution of your program.31+ When declaring it in a [callback](https://typer.tiangolo.com/tutorial/options/callback-and-context/) function,32+ you can access this additional information.33+ """34+35 pass36 37 38 class FileText(io.TextIOWrapper):39+ """40+ Gives you a file-like object for reading text, and you will get a `str` data from it.41+ The default mode of this class is `mode="r"`.42+43+ **Example**44+45+ ```python46+ from typing import Annotated47+48+ import typer49+50+ app = typer.Typer()51+52+ @app.command()53+ def main(config: Annotated[typer.FileText, typer.Option()]):54+ for line in config:55+ print(f"Config line: {line}")56+57+ if __name__ == "__main__":58+ app()59+ ```60+ """61+62 pass63 64 65 class FileTextWrite(FileText):66+ """67+ You can use this class for writing text. Alternatively, you can use `FileText` with `mode="w"`.68+ The default mode of this class is `mode="w"`.69+70+ **Example**71+72+ ```python73+ from typing import Annotated74+75+ import typer76+77+ app = typer.Typer()78+79+ @app.command()80+ def main(config: Annotated[typer.FileTextWrite, typer.Option()]):81+ config.write("Some config written by the app")82+ print("Config written")83+84+ if __name__ == "__main__":85+ app()86+ ```87+ """88+89 pass90 91 92 class FileBinaryRead(io.BufferedReader):93+ """94+ You can use this class to read binary data, receiving `bytes`.95+ The default mode of this class is `mode="rb"`.96+ It is useful for reading binary files like images:97+98+ **Example**99+100+ ```python101+ from typing import Annotated102+103+ import typer104+105+ app = typer.Typer()106+107+ @app.command()108+ def main(file: Annotated[typer.FileBinaryRead, typer.Option()]):109+ processed_total = 0110+ for bytes_chunk in file:111+ # Process the bytes in bytes_chunk112+ processed_total += len(bytes_chunk)113+ print(f"Processed bytes total: {processed_total}")114+115+ if __name__ == "__main__":116+ app()117+ ```118+ """119+120 pass121 122 123 class FileBinaryWrite(io.BufferedWriter):124+ """125+ You can use this class to write binary data: you pass `bytes` to it instead of strings.126+ The default mode of this class is `mode="wb"`.127+ It is useful for writing binary files like images:128+129+ **Example**130+131+ ```python132+ from typing import Annotated133+134+ import typer135+136+ app = typer.Typer()137+138+ @app.command()139+ def main(file: Annotated[typer.FileBinaryWrite, typer.Option()]):140+ first_line_str = "some settings\\n"141+ # You cannot write str directly to a binary file; encode it first142+ first_line_bytes = first_line_str.encode("utf-8")143+ # Then you can write the bytes144+ file.write(first_line_bytes)145+ # This is already bytes, it starts with b"146+ second_line = b"la cig\xc3\xbce\xc3\xb1a trae al ni\xc3\xb1o"147+ file.write(second_line)148+ print("Binary file written")149+150+ if __name__ == "__main__":151+ app()152+ ```153+ """154+155 pass156 157 158 class CallbackParam(click.Parameter):159+ """160+ In a callback function, you can declare a function parameter with type `CallbackParam`161+ to access the specific Click [`Parameter`](https://click.palletsprojects.com/en/stable/api/#click.Parameter) object.162+ """163+164 pass165 166 167 class DefaultPlaceholder:489 unmodified linesmodified:typer/params.py+1447 added-90 removed
1-from typing import TYPE_CHECKING, Any, Callable, Optional, Union, overload1+from typing import TYPE_CHECKING, Annotated, Any, Callable, Optional, Union, overload2 3 import click4+from annotated_doc import Doc5 6 from .models import ArgumentInfo, OptionInfo7 8 if TYPE_CHECKING: # pragma: no cover133 unmodified lines142 143 144 def Option(145 # Parameter145- default: Optional[Any] = ...,146- *param_decls: str,147- callback: Optional[Callable[..., Any]] = None,148- metavar: Optional[str] = None,149- expose_value: bool = True,150- is_eager: bool = False,151- envvar: Optional[Union[str, list[str]]] = None,152- # Note that shell_complete is not fully supported and will be removed in future versions146+ default: Annotated[147+ Optional[Any],148+ Doc(149+ """150+ Usually, [CLI options](https://typer.tiangolo.com/tutorial/options/) are optional and have a default value, passed on like this:151+152+ **Example**153+154+ ```python155+ @app.command()156+ def main(network: str = typer.Option("CNN")):157+ print(f"Training neural network of type: {network}")158+ ```159+160+ Note that this usage is deprecated, and we recommend to use `Annotated` instead:161+ ```162+ @app.command()163+ def main(network: Annotated[str, typer.Option()] = "CNN"):164+ print(f"Hello {name}!")165+ ```166+167+ You can also use `...` ([Ellipsis](https://docs.python.org/3/library/constants.html#Ellipsis)) as the "default" value to clarify that this is a required CLI option.168+ """169+ ),170+ ] = ...,171+ *param_decls: Annotated[172+ str,173+ Doc(174+ """175+ Positional argument that defines how users can call this option on the command line. This may be one or multiple aliases, all strings.176+ If not defined, Typer will automatically use the function parameter as default name.177+ See [the tutorial about CLI Option Names](https://typer.tiangolo.com/tutorial/options/name/) for more details.178+179+ **Example**180+181+ ```python182+ @app.command()183+ def main(user_name: Annotated[str, typer.Option("--user", "-u", "-x")]):184+ print(f"Hello {user_name}")185+ ```186+ """187+ ),188+ ],189+ callback: Annotated[190+ Optional[Callable[..., Any]],191+ Doc(192+ """193+ Add a callback to this CLI Option, to execute additional logic after its value was received from the terminal.194+ See [the tutorial about callbacks](https://typer.tiangolo.com/tutorial/options/callback-and-context/) for more details.195+196+ **Example**197+198+ ```python199+ def name_callback(value: str):200+ if value != "Deadpool":201+ raise typer.BadParameter("Only Deadpool is allowed")202+ return value203+204+ @app.command()205+ def main(name: Annotated[str, typer.Option(callback=name_callback)]):206+ print(f"Hello {name}")207+ ```208+ """209+ ),210+ ] = None,211+ metavar: Annotated[212+ Optional[str],213+ Doc(214+ """215+ Customize the name displayed in the [help text](https://typer.tiangolo.com/tutorial/options/help/) to represent this CLI option.216+ Note that this doesn't influence the way the option must be called.217+218+ **Example**219+220+ ```python221+ @app.command()222+ def main(user: Annotated[str, typer.Option(metavar="User name")]):223+ print(f"Hello {user}")224+ ```225+ """226+ ),227+ ] = None,228+ expose_value: Annotated[229+ bool,230+ Doc(231+ """232+ **Note**: you probably shouldn't use this parameter, it is inherited from Click and supported for compatibility.233+234+ ---235+236+ If this is `True` then the value is passed onwards to the command callback and stored on the context, otherwise it’s skipped.237+ """238+ ),239+ ] = True,240+ is_eager: Annotated[241+ bool,242+ Doc(243+ """244+ Mark a CLI Option to be "eager", ensuring it gets processed before other CLI parameters. This could be relevant when there are other parameters with callbacks that could exit the program early.245+ For more information and an extended example, see the documentation [here](https://typer.tiangolo.com/tutorial/options/version/#fix-with-is_eager).246+ """247+ ),248+ ] = False,249+ envvar: Annotated[250+ Optional[Union[str, list[str]]],251+ Doc(252+ """253+ Configure a CLI Option to read its value from an environment variable if it is not provided in the command line.254+ For more information, see the [documentation on Environment Variables](https://typer.tiangolo.com/tutorial/arguments/envvar/).255+256+ **Example**257+258+ ```python259+ @app.command()260+ def main(user: Annotated[str, typer.Option(envvar="ME")]):261+ print(f"Hello {user}")262+ ```263+ """264+ ),265+ ] = None,266 # TODO: Remove shell_complete in a future version (after 0.16.0)267+ shell_complete: Annotated[154- shell_complete: Optional[155- Callable[156- [click.Context, click.Parameter, str],157- Union[list["click.shell_completion.CompletionItem"], list[str]],158- ]268+ Optional[269+ Callable[270+ [click.Context, click.Parameter, str],271+ Union[list["click.shell_completion.CompletionItem"], list[str]],272+ ]273+ ],274+ Doc(275+ """276+ **Note**: you probably shouldn't use this parameter, it is inherited from Click and supported for compatibility.277+ It is however not fully functional, and will likely be removed in future versions.278+ """279+ ),280 ] = None,160- autocompletion: Optional[Callable[..., Any]] = None,161- default_factory: Optional[Callable[[], Any]] = None,281+ autocompletion: Annotated[282+ Optional[Callable[..., Any]],283+ Doc(284+ """285+ Provide a custom function that helps to autocomplete the values of this CLI Option.286+ See [the tutorial on parameter autocompletion](https://typer.tiangolo.com/tutorial/options-autocompletion) for more details.287+288+ **Example**289+290+ ```python291+ def complete():292+ return ["Me", "Myself", "I"]293+294+ @app.command()295+ def main(name: Annotated[str, typer.Option(autocompletion=complete)]):296+ print(f"Hello {name}")297+ ```298+ """299+ ),300+ ] = None,301+ default_factory: Annotated[302+ Optional[Callable[[], Any]],303+ Doc(304+ """305+ Provide a custom function that dynamically generates a [default](https://typer.tiangolo.com/tutorial/arguments/default) for this CLI Option.306+307+ **Example**308+309+ ```python310+ def get_name():311+ return random.choice(["Me", "Myself", "I"])312+313+ @app.command()314+ def main(name: Annotated[str, typer.Option(default_factory=get_name)]):315+ print(f"Hello {name}")316+ ```317+ """318+ ),319+ ] = None,320 # Custom type163- parser: Optional[Callable[[str], Any]] = None,164- click_type: Optional[click.ParamType] = None,321+ parser: Annotated[322+ Optional[Callable[[str], Any]],323+ Doc(324+ """325+ Use your own custom types in Typer applications by defining a `parser` function that parses input into your own types:326+327+ **Example**328+329+ ```python330+ class CustomClass:331+ def __init__(self, value: str):332+ self.value = value333+334+ def __str__(self):335+ return f"<CustomClass: value={self.value}>"336+337+ def my_parser(value: str):338+ return CustomClass(value * 2)339+340+ @app.command()341+ def main(opt: Annotated[CustomClass, typer.Option(parser=my_parser)] = "Foo"):342+ print(f"--opt is {opt}")343+ ```344+ """345+ ),346+ ] = None,347+ click_type: Annotated[348+ Optional[click.ParamType],349+ Doc(350+ """351+ Define this parameter to use a [custom Click type](https://click.palletsprojects.com/en/stable/parameters/#implementing-custom-types) in your Typer applications.352+353+ **Example**354+355+ ```python356+ class MyClass:357+ def __init__(self, value: str):358+ self.value = value359+360+ def __str__(self):361+ return f"<MyClass: value={self.value}>"362+363+ class MyParser(click.ParamType):364+ name = "MyClass"365+366+ def convert(self, value, param, ctx):367+ return MyClass(value * 3)368+369+ @app.command()370+ def main(opt: Annotated[MyClass, typer.Option(click_type=MyParser())] = "Foo"):371+ print(f"--opt is {opt}")372+ ```373+ """374+ ),375+ ] = None,376 # Option166- show_default: Union[bool, str] = True,167- prompt: Union[bool, str] = False,168- confirmation_prompt: bool = False,169- prompt_required: bool = True,170- hide_input: bool = False,377+ show_default: Annotated[378+ Union[bool, str],379+ Doc(380+ """381+ When set to `False`, don't show the default value of this CLI Option in the [help text](https://typer.tiangolo.com/tutorial/options/help/).382+383+ **Example**384+385+ ```python386+ @app.command()387+ def main(name: Annotated[str, typer.Option(show_default=False)] = "Rick"):388+ print(f"Hello {name}")389+ ```390+ """391+ ),392+ ] = True,393+ prompt: Annotated[394+ Union[bool, str],395+ Doc(396+ """397+ When set to `True`, a prompt will appear to ask for the value of this CLI Option if it was not provided:398+399+ **Example**400+401+ ```python402+ @app.command()403+ def main(name: str, lastname: Annotated[str, typer.Option(prompt=True)]):404+ print(f"Hello {name} {lastname}")405+ ```406+ """407+ ),408+ ] = False,409+ confirmation_prompt: Annotated[410+ bool,411+ Doc(412+ """413+ When set to `True`, a user will need to type a prompted value twice (may be useful for passwords etc.).414+415+ **Example**416+417+ ```python418+ @app.command()419+ def main(project: Annotated[str, typer.Option(prompt=True, confirmation_prompt=True)]):420+ print(f"Deleting project {project}")421+ ```422+ """423+ ),424+ ] = False,425+ prompt_required: Annotated[426+ bool,427+ Doc(428+ """429+ **Note**: you probably shouldn't use this parameter, it is inherited from Click and supported for compatibility.430+431+ ---432+433+ If this is `False` then a prompt is only shown if the option's flag is given without a value.434+ """435+ ),436+ ] = True,437+ hide_input: Annotated[438+ bool,439+ Doc(440+ """441+ When you've configured a prompt, for instance for [querying a password](https://typer.tiangolo.com/tutorial/options/password/),442+ don't show anything on the screen while the user is typing the value.443+444+ **Example**445+446+ ```python447+ @app.command()448+ def login(449+ name: str,450+ password: Annotated[str, typer.Option(prompt=True, hide_input=True)],451+ ):452+ print(f"Hello {name}. Doing something very secure with password.")453+ ```454+ """455+ ),456+ ] = False,457 # TODO: remove is_flag and flag_value in a future release172- is_flag: Optional[bool] = None,173- flag_value: Optional[Any] = None,174- count: bool = False,175- allow_from_autoenv: bool = True,176- help: Optional[str] = None,177- hidden: bool = False,178- show_choices: bool = True,179- show_envvar: bool = True,458+ is_flag: Annotated[459+ Optional[bool],460+ Doc(461+ """462+ **Note**: you probably shouldn't use this parameter, it is inherited from Click and supported for compatibility.463+ It is however not fully functional, and will likely be removed in future versions.464+ """465+ ),466+ ] = None,467+ flag_value: Annotated[468+ Optional[Any],469+ Doc(470+ """471+ **Note**: you probably shouldn't use this parameter, it is inherited from Click and supported for compatibility.472+ It is however not fully functional, and will likely be removed in future versions.473+ """474+ ),475+ ] = None,476+ count: Annotated[477+ bool,478+ Doc(479+ """480+ Make a CLI Option work as a [counter](https://typer.tiangolo.com/tutorial/parameter-types/number/#counter-cli-options).481+ The CLI option will have the `int` value representing the number of times the option was used on the command line.482+483+ **Example**484+485+ ```python486+ @app.command()487+ def main(verbose: Annotated[int, typer.Option("--verbose", "-v", count=True)] = 0):488+ print(f"Verbose level is {verbose}")489+ ```490+ """491+ ),492+ ] = False,493+ allow_from_autoenv: Annotated[494+ bool,495+ Doc(496+ """497+ **Note**: you probably shouldn't use this parameter, it is inherited from Click and supported for compatibility.498+499+ ---500+501+ If this is enabled then the value of this parameter will be pulled from an environment variable in case a prefix is defined on the context.502+ """503+ ),504+ ] = True,505+ help: Annotated[506+ Optional[str],507+ Doc(508+ """509+ Help text for this CLI Option.510+ See [the tutorial about CLI Options with help](https://typer.tiangolo.com/tutorial/options/help/) for more dedails.511+512+ **Example**513+514+ ```python515+ @app.command()516+ def greet(name: Annotated[str, typer.Option(help="Person to greet")] = "Deadpool"):517+ print(f"Hello {name}")518+ ```519+ """520+ ),521+ ] = None,522+ hidden: Annotated[523+ bool,524+ Doc(525+ """526+ Hide this CLI Option from [help outputs](https://typer.tiangolo.com/tutorial/options/help). `False` by default.527+528+ **Example**529+530+ ```python531+ @app.command()532+ def greet(name: Annotated[str, typer.Option(hidden=True)] = "Deadpool"):533+ print(f"Hello {name}")534+ ```535+ """536+ ),537+ ] = False,538+ show_choices: Annotated[539+ bool,540+ Doc(541+ """542+ **Note**: you probably shouldn't use this parameter, it is inherited from Click and supported for compatibility.543+544+ ---545+546+ When set to `False`, this suppresses choices from being displayed inline when `prompt` is used.547+ """548+ ),549+ ] = True,550+ show_envvar: Annotated[551+ bool,552+ Doc(553+ """554+ When an ["envvar"](https://typer.tiangolo.com/tutorial/arguments/envvar) is defined, prevent it from showing up in the help text:555+556+ **Example**557+558+ ```python559+ @app.command()560+ def main(user: Annotated[str, typer.Option(envvar="ME", show_envvar=False)]):561+ print(f"Hello {user}")562+ ```563+ """564+ ),565+ ] = True,566 # Choice181- case_sensitive: bool = True,567+ case_sensitive: Annotated[568+ bool,569+ Doc(570+ """571+ For a CLI Option representing an [Enum (choice)](https://typer.tiangolo.com/tutorial/parameter-types/enum),572+ you can allow case-insensitive matching with this parameter:573+574+ **Example**575+576+ ```python577+ from enum import Enum578+579+ class NeuralNetwork(str, Enum):580+ simple = "simple"581+ conv = "conv"582+ lstm = "lstm"583+584+ @app.command()585+ def main(586+ network: Annotated[NeuralNetwork, typer.Option(case_sensitive=False)]):587+ print(f"Training neural network of type: {network.value}")588+ ```589+590+ With this setting, "LSTM" or "lstm" will both be valid values that will be resolved to `NeuralNetwork.lstm`.591+ """592+ ),593+ ] = True,594 # Numbers183- min: Optional[Union[int, float]] = None,184- max: Optional[Union[int, float]] = None,185- clamp: bool = False,595+ min: Annotated[596+ Optional[Union[int, float]],597+ Doc(598+ """599+ For a CLI Option representing a [number](https://typer.tiangolo.com/tutorial/parameter-types/number/) (`int` or `float`),600+ you can define numeric validations with `min` and `max` values:601+602+ **Example**603+604+ ```python605+ @app.command()606+ def main(607+ user: Annotated[str, typer.Argument()],608+ user_id: Annotated[int, typer.Option(min=1, max=1000)],609+ ):610+ print(f"ID for {user} is {user_id}")611+ ```612+613+ If the user attempts to input an invalid number, an error will be shown, explaining why the value is invalid.614+ """615+ ),616+ ] = None,617+ max: Annotated[618+ Optional[Union[int, float]],619+ Doc(620+ """621+ For a CLI Option representing a [number](https://typer.tiangolo.com/tutorial/parameter-types/number/) (`int` or `float`),622+ you can define numeric validations with `min` and `max` values:623+624+ **Example**625+626+ ```python627+ @app.command()628+ def main(629+ user: Annotated[str, typer.Argument()],630+ user_id: Annotated[int, typer.Option(min=1, max=1000)],631+ ):632+ print(f"ID for {user} is {user_id}")633+ ```634+635+ If the user attempts to input an invalid number, an error will be shown, explaining why the value is invalid.636+ """637+ ),638+ ] = None,639+ clamp: Annotated[640+ bool,641+ Doc(642+ """643+ For a CLI Option representing a [number](https://typer.tiangolo.com/tutorial/parameter-types/number/) and that is bounded by using `min` and/or `max`,644+ you can opt to use the closest minimum or maximum value instead of raising an error when the value is out of bounds. This is done by setting `clamp` to `True`.645+646+ **Example**647+648+ ```python649+ @app.command()650+ def main(651+ user: Annotated[str, typer.Argument()],652+ user_id: Annotated[int, typer.Option(min=1, max=1000, clamp=True)],653+ ):654+ print(f"ID for {user} is {user_id}")655+ ```656+657+ If the user attempts to input 3420 for `user_id`, this will internally be converted to `1000`.658+ """659+ ),660+ ] = False,661 # DateTime187- formats: Optional[list[str]] = None,662+ formats: Annotated[663+ Optional[list[str]],664+ Doc(665+ """666+ For a CLI Option representing a [DateTime object](https://typer.tiangolo.com/tutorial/parameter-types/datetime),667+ you can customize the formats that can be parsed automatically:668+669+ **Example**670+671+ ```python672+ from datetime import datetime673+674+ @app.command()675+ def main(676+ birthday: Annotated[677+ datetime,678+ typer.Option(679+ formats=["%Y-%m-%d", "%Y-%m-%d %H:%M:%S", "%m/%d/%Y"]680+ ),681+ ],682+ ):683+ print(f"Birthday defined at: {birthday}")684+ ```685+ """686+ ),687+ ] = None,688 # File189- mode: Optional[str] = None,190- encoding: Optional[str] = None,191- errors: Optional[str] = "strict",192- lazy: Optional[bool] = None,193- atomic: bool = False,689+ mode: Annotated[690+ Optional[str],691+ Doc(692+ """693+ For a CLI Option representing a [File object](https://typer.tiangolo.com/tutorial/parameter-types/file/),694+ you can customize the mode to open the file with. If unset, Typer will set a [sensible value by default](https://typer.tiangolo.com/tutorial/parameter-types/file/#advanced-mode).695+696+ **Example**697+698+ ```python699+ @app.command()700+ def main(config: Annotated[typer.FileText, typer.Option(mode="a")]):701+ config.write("This is a single line\\n")702+ print("Config line written")703+ ```704+ """705+ ),706+ ] = None,707+ encoding: Annotated[708+ Optional[str],709+ Doc(710+ """711+ Customize the encoding of this CLI Option represented by a [File object](https://typer.tiangolo.com/tutorial/parameter-types/file/).712+713+ **Example**714+715+ ```python716+ @app.command()717+ def main(config: Annotated[typer.FileText, typer.Option(encoding="utf-8")]):718+ config.write("All the text gets written\\n")719+ ```720+ """721+ ),722+ ] = None,723+ errors: Annotated[724+ Optional[str],725+ Doc(726+ """727+ **Note**: you probably shouldn't use this parameter, it is inherited from Click and supported for compatibility.728+729+ ---730+731+ The error handling mode.732+ """733+ ),734+ ] = "strict",735+ lazy: Annotated[736+ Optional[bool],737+ Doc(738+ """739+ For a CLI Option representing a [File object](https://typer.tiangolo.com/tutorial/parameter-types/file/),740+ by default the file will not be created until you actually start writing to it.741+ You can change this behaviour by setting this parameter.742+ By default, it's set to `True` for writing and to `False` for reading.743+744+ **Example**745+746+ ```python747+ @app.command()748+ def main(config: Annotated[typer.FileText, typer.Option(mode="a", lazy=False)]):749+ config.write("This is a single line\\n")750+ print("Config line written")751+ ```752+ """753+ ),754+ ] = None,755+ atomic: Annotated[756+ bool,757+ Doc(758+ """759+ For a CLI Option representing a [File object](https://typer.tiangolo.com/tutorial/parameter-types/file/),760+ you can ensure that all write instructions first go into a temporal file, and are only moved to the final destination after completing761+ by setting `atomic` to `True`. This can be useful for files with potential concurrent access.762+763+ **Example**764+765+ ```python766+ @app.command()767+ def main(config: Annotated[typer.FileText, typer.Option(mode="a", atomic=True)]):768+ config.write("All the text")769+ ```770+ """771+ ),772+ ] = False,773 # Path195- exists: bool = False,196- file_okay: bool = True,197- dir_okay: bool = True,198- writable: bool = False,199- readable: bool = True,200- resolve_path: bool = False,201- allow_dash: bool = False,202- path_type: Union[None, type[str], type[bytes]] = None,774+ exists: Annotated[775+ bool,776+ Doc(777+ """778+ When set to `True` for a [`Path` CLI Option](https://typer.tiangolo.com/tutorial/parameter-types/path/),779+ additional validation is performed to check that the file or directory exists. If not, the value will be invalid.780+781+ **Example**782+783+ ```python784+ from pathlib import Path785+786+ @app.command()787+ def main(config: Annotated[Path, typer.Option(exists=True)]):788+ text = config.read_text()789+ print(f"Config file contents: {text}")790+ ```791+ """792+ ),793+ ] = False,794+ file_okay: Annotated[795+ bool,796+ Doc(797+ """798+ Determine whether or not a [`Path` CLI Option](https://typer.tiangolo.com/tutorial/parameter-types/path/)799+ is allowed to refer to a file. When this is set to `False`, the application will raise a validation error when a path to a file is given.800+801+ **Example**802+803+ ```python804+ from pathlib import Path805+806+ @app.command()807+ def main(config: Annotated[Path, typer.Option(exists=True, file_okay=False)]):808+ print(f"Directory listing: {[x.name for x in config.iterdir()]}")809+ ```810+ """811+ ),812+ ] = True,813+ dir_okay: Annotated[814+ bool,815+ Doc(816+ """817+ Determine whether or not a [`Path` CLI Option](https://typer.tiangolo.com/tutorial/parameter-types/path/)818+ is allowed to refer to a directory. When this is set to `False`, the application will raise a validation error when a path to a directory is given.819+820+ **Example**821+822+ ```python823+ from pathlib import Path824+825+ @app.command()826+ def main(config: Annotated[Path, typer.Argument(exists=True, dir_okay=False)]):827+ text = config.read_text()828+ print(f"Config file contents: {text}")829+ ```830+ """831+ ),832+ ] = True,833+ writable: Annotated[834+ bool,835+ Doc(836+ """837+ Whether or not to perform a writable check for this [`Path` CLI Option](https://typer.tiangolo.com/tutorial/parameter-types/path/).838+839+ **Example**840+841+ ```python842+ from pathlib import Path843+844+ @app.command()845+ def main(config: Annotated[Path, typer.Option(writable=True)]):846+ config.write_text("All the text")847+ ```848+ """849+ ),850+ ] = False,851+ readable: Annotated[852+ bool,853+ Doc(854+ """855+ Whether or not to perform a readable check for this [`Path` CLI Option](https://typer.tiangolo.com/tutorial/parameter-types/path/).856+857+ **Example**858+859+ ```python860+ from pathlib import Path861+862+ @app.command()863+ def main(config: Annotated[Path, typer.Option(readable=True)]):864+ config.read_text("All the text")865+ ```866+ """867+ ),868+ ] = True,869+ resolve_path: Annotated[870+ bool,871+ Doc(872+ """873+ Whether or not to fully resolve the path of this [`Path` CLI Option](https://typer.tiangolo.com/tutorial/parameter-types/path/),874+ meaning that the path becomes absolute and symlinks are resolved.875+876+ **Example**877+878+ ```python879+ from pathlib import Path880+881+ @app.command()882+ def main(config: Annotated[Path, typer.Option(resolve_path=True)]):883+ config.read_text("All the text")884+ ```885+ """886+ ),887+ ] = False,888+ allow_dash: Annotated[889+ bool,890+ Doc(891+ """892+ When set to `True`, a single dash for this [`Path` CLI Option](https://typer.tiangolo.com/tutorial/parameter-types/path/)893+ would be a valid value, indicating standard streams. This is a more advanced use-case.894+ """895+ ),896+ ] = False,897+ path_type: Annotated[898+ Union[None, type[str], type[bytes]],899+ Doc(900+ """901+ A string type that will be used to represent this [`Path` argument](https://typer.tiangolo.com/tutorial/parameter-types/path/).902+ The default is `None` which means the return value will be either bytes or unicode, depending on what makes most sense given the input data.903+ This is a more advanced use-case.904+ """905+ ),906+ ] = None,907 # Rich settings204- rich_help_panel: Union[str, None] = None,908+ rich_help_panel: Annotated[909+ Union[str, None],910+ Doc(911+ """912+ Set the panel name where you want this CLI Option to be shown in the [help text](https://typer.tiangolo.com/tutorial/arguments/help).913+914+ **Example**915+916+ ```python917+ @app.command()918+ def main(919+ name: Annotated[str, typer.Argument(help="Who to greet")],920+ age: Annotated[str, typer.Option(help="Their age", rich_help_panel="Data")],921+ ):922+ print(f"Hello {name} of age {age}")923+ ```924+ """925+ ),926+ ] = None,927 ) -> Any:928+ """929+ A [CLI Option](https://typer.tiangolo.com/tutorial/options) is a parameter to your command line application that is called with a single or double dash, something like `--verbose` or `-v`.930+931+ Often, CLI Options are optional, meaning that users can omit them from the command. However, you can set them to be required by using `Annotated`932+ and omitting a default value.933+934+ ## Example935+936+ ```python937+ @app.command()938+ def register(939+ user: Annotated[str, typer.Argument()],940+ age: Annotated[int, typer.Option(min=18)],941+ ):942+ print(f"User is {user}")943+ print(f"--age is {age}")944+ ```945+946+ Note how in this example, `--age` is a required CLI Option.947+ """948 return OptionInfo(949 # Parameter950 default=default,951 param_decls=param_decls,165 unmodified lines1117 1118 1119 def Argument(1120 # Parameter379- default: Optional[Any] = ...,1121+ default: Annotated[1122+ Optional[Any],1123+ Doc(1124+ """1125+ By default, CLI arguments are required. However, by giving them a default value they become [optional](https://typer.tiangolo.com/tutorial/arguments/optional):1126+1127+ **Example**1128+1129+ ```python1130+ @app.command()1131+ def main(name: str = typer.Argument("World")):1132+ print(f"Hello {name}!")1133+ ```1134+1135+ Note that this usage is deprecated, and we recommend to use `Annotated` instead:1136+ ```python1137+ @app.command()1138+ def main(name: Annotated[str, typer.Argument()] = "World"):1139+ print(f"Hello {name}!")1140+ ```1141+ """1142+ ),1143+ ] = ...,1144 *,381- callback: Optional[Callable[..., Any]] = None,382- metavar: Optional[str] = None,383- expose_value: bool = True,384- is_eager: bool = False,385- envvar: Optional[Union[str, list[str]]] = None,386- # Note that shell_complete is not fully supported and will be removed in future versions1145+ callback: Annotated[1146+ Optional[Callable[..., Any]],1147+ Doc(1148+ """1149+ Add a callback to this CLI Argument, to execute additional logic with the value received from the terminal.1150+ See [the tutorial about callbacks](https://typer.tiangolo.com/tutorial/options/callback-and-context/) for more details.1151+1152+ **Example**1153+1154+ ```python1155+ def name_callback(value: str):1156+ if value != "Deadpool":1157+ raise typer.BadParameter("Only Deadpool is allowed")1158+ return value1159+1160+ @app.command()1161+ def main(name: Annotated[str, typer.Argument(callback=name_callback)]):1162+ print(f"Hello {name}")1163+ ```1164+ """1165+ ),1166+ ] = None,1167+ metavar: Annotated[1168+ Optional[str],1169+ Doc(1170+ """1171+ Customize the name displayed in the help text to represent this CLI Argument.1172+ By default, it will be the same name you declared, in uppercase.1173+ See [the tutorial about CLI Arguments with Help](https://typer.tiangolo.com/tutorial/arguments/help/#custom-help-name-metavar) for more details.1174+1175+ **Example**1176+1177+ ```python1178+ @app.command()1179+ def main(name: Annotated[str, typer.Argument(metavar="✨username✨")]):1180+ print(f"Hello {name}")1181+ ```1182+ """1183+ ),1184+ ] = None,1185+ expose_value: Annotated[1186+ bool,1187+ Doc(1188+ """1189+ **Note**: you probably shouldn't use this parameter, it is inherited from Click and supported for compatibility.1190+1191+ ---1192+1193+ If this is `True` then the value is passed onwards to the command callback and stored on the context, otherwise it’s skipped.1194+ """1195+ ),1196+ ] = True,1197+ is_eager: Annotated[1198+ bool,1199+ Doc(1200+ """1201+ Set an argument to "eager" to ensure it gets processed before other CLI parameters. This could be relevant when there are other parameters with callbacks that could exit the program early.1202+ For more information and an extended example, see the documentation [here](https://typer.tiangolo.com/tutorial/options/version/#fix-with-is_eager).1203+ """1204+ ),1205+ ] = False,1206+ envvar: Annotated[1207+ Optional[Union[str, list[str]]],1208+ Doc(1209+ """1210+ Configure an argument to read a value from an environment variable if it is not provided in the command line as a CLI argument.1211+ For more information, see the [documentation on Environment Variables](https://typer.tiangolo.com/tutorial/arguments/envvar/).1212+1213+ **Example**1214+1215+ ```python1216+ @app.command()1217+ def main(name: Annotated[str, typer.Argument(envvar="ME")]):1218+ print(f"Hello Mr. {name}")1219+ ```1220+ """1221+ ),1222+ ] = None,1223 # TODO: Remove shell_complete in a future version (after 0.16.0)1224+ shell_complete: Annotated[388- shell_complete: Optional[389- Callable[390- [click.Context, click.Parameter, str],391- Union[list["click.shell_completion.CompletionItem"], list[str]],392- ]1225+ Optional[1226+ Callable[1227+ [click.Context, click.Parameter, str],1228+ Union[list["click.shell_completion.CompletionItem"], list[str]],1229+ ]1230+ ],1231+ Doc(1232+ """1233+ **Note**: you probably shouldn't use this parameter, it is inherited from Click and supported for compatibility.1234+ It is however not fully functional, and will likely be removed in future versions.1235+ """1236+ ),1237 ] = None,394- autocompletion: Optional[Callable[..., Any]] = None,395- default_factory: Optional[Callable[[], Any]] = None,1238+ autocompletion: Annotated[1239+ Optional[Callable[..., Any]],1240+ Doc(1241+ """1242+ Provide a custom function that helps to autocomplete the values of this CLI Argument.1243+ See [the tutorial on parameter autocompletion](https://typer.tiangolo.com/tutorial/options-autocompletion) for more details.1244+1245+ **Example**1246+1247+ ```python1248+ def complete():1249+ return ["Me", "Myself", "I"]1250+1251+ @app.command()1252+ def main(name: Annotated[str, typer.Argument(autocompletion=complete)]):1253+ print(f"Hello {name}")1254+ ```1255+ """1256+ ),1257+ ] = None,1258+ default_factory: Annotated[1259+ Optional[Callable[[], Any]],1260+ Doc(1261+ """1262+ Provide a custom function that dynamically generates a [default](https://typer.tiangolo.com/tutorial/arguments/default) for this CLI Argument.1263+1264+ **Example**1265+1266+ ```python1267+ def get_name():1268+ return random.choice(["Me", "Myself", "I"])1269+1270+ @app.command()1271+ def main(name: Annotated[str, typer.Argument(default_factory=get_name)]):1272+ print(f"Hello {name}")1273+ ```1274+ """1275+ ),1276+ ] = None,1277 # Custom type397- parser: Optional[Callable[[str], Any]] = None,398- click_type: Optional[click.ParamType] = None,1278+ parser: Annotated[1279+ Optional[Callable[[str], Any]],1280+ Doc(1281+ """1282+ Use your own custom types in Typer applications by defining a `parser` function that parses input into your own types:1283+1284+ **Example**1285+1286+ ```python1287+ class CustomClass:1288+ def __init__(self, value: str):1289+ self.value = value1290+1291+ def __str__(self):1292+ return f"<CustomClass: value={self.value}>"1293+1294+ def my_parser(value: str):1295+ return CustomClass(value * 2)1296+1297+ @app.command()1298+ def main(arg: Annotated[CustomClass, typer.Argument(parser=my_parser):1299+ print(f"arg is {arg}")1300+ ```1301+ """1302+ ),1303+ ] = None,1304+ click_type: Annotated[1305+ Optional[click.ParamType],1306+ Doc(1307+ """1308+ Define this parameter to use a [custom Click type](https://click.palletsprojects.com/en/stable/parameters/#implementing-custom-types) in your Typer applications.1309+1310+ **Example**1311+1312+ ```python1313+ class MyClass:1314+ def __init__(self, value: str):1315+ self.value = value1316+1317+ def __str__(self):1318+ return f"<MyClass: value={self.value}>"1319+1320+ class MyParser(click.ParamType):1321+ name = "MyClass"1322+1323+ def convert(self, value, param, ctx):1324+ return MyClass(value * 3)1325+1326+ @app.command()1327+ def main(arg: Annotated[MyClass, typer.Argument(click_type=MyParser())]):1328+ print(f"arg is {arg}")1329+ ```1330+ """1331+ ),1332+ ] = None,1333 # TyperArgument400- show_default: Union[bool, str] = True,401- show_choices: bool = True,402- show_envvar: bool = True,403- help: Optional[str] = None,404- hidden: bool = False,1334+ show_default: Annotated[1335+ Union[bool, str],1336+ Doc(1337+ """1338+ When set to `False`, don't show the default value of this CLI Argument in the [help text](https://typer.tiangolo.com/tutorial/arguments/help/).1339+1340+ **Example**1341+1342+ ```python1343+ @app.command()1344+ def main(name: Annotated[str, typer.Argument(show_default=False)] = "Rick"):1345+ print(f"Hello {name}")1346+ ```1347+ """1348+ ),1349+ ] = True,1350+ show_choices: Annotated[1351+ bool,1352+ Doc(1353+ """1354+ **Note**: you probably shouldn't use this parameter, it is inherited from Click and supported for compatibility.1355+1356+ ---1357+1358+ When set to `False`, this suppresses choices from being displayed inline when `prompt` is used.1359+ """1360+ ),1361+ ] = True,1362+ show_envvar: Annotated[1363+ bool,1364+ Doc(1365+ """1366+ When an ["envvar"](https://typer.tiangolo.com/tutorial/arguments/envvar) is defined, prevent it from showing up in the help text:1367+1368+ **Example**1369+1370+ ```python1371+ @app.command()1372+ def main(name: Annotated[str, typer.Argument(envvar="ME", show_envvar=False)]):1373+ print(f"Hello Mr. {name}")1374+ ```1375+ """1376+ ),1377+ ] = True,1378+ help: Annotated[1379+ Optional[str],1380+ Doc(1381+ """1382+ Help text for this CLI Argument.1383+ See [the tutorial about CLI Arguments with help](https://typer.tiangolo.com/tutorial/arguments/help/) for more dedails.1384+1385+ **Example**1386+1387+ ```python1388+ @app.command()1389+ def greet(name: Annotated[str, typer.Argument(help="Person to greet")]):1390+ print(f"Hello {name}")1391+ ```1392+ """1393+ ),1394+ ] = None,1395+ hidden: Annotated[1396+ bool,1397+ Doc(1398+ """1399+ Hide this CLI Argument from [help outputs](https://typer.tiangolo.com/tutorial/arguments/help). `False` by default.1400+1401+ **Example**1402+1403+ ```python1404+ @app.command()1405+ def main(name: Annotated[str, typer.Argument(hidden=True)] = "World"):1406+ print(f"Hello {name}")1407+ ```1408+ """1409+ ),1410+ ] = False,1411 # Choice406- case_sensitive: bool = True,1412+ case_sensitive: Annotated[1413+ bool,1414+ Doc(1415+ """1416+ For a CLI Argument representing an [Enum (choice)](https://typer.tiangolo.com/tutorial/parameter-types/enum),1417+ you can allow case-insensitive matching with this parameter:1418+1419+ **Example**1420+1421+ ```python1422+ from enum import Enum1423+1424+ class NeuralNetwork(str, Enum):1425+ simple = "simple"1426+ conv = "conv"1427+ lstm = "lstm"1428+1429+ @app.command()1430+ def main(1431+ network: Annotated[NeuralNetwork, typer.Argument(case_sensitive=False)]):1432+ print(f"Training neural network of type: {network.value}")1433+ ```1434+1435+ With this setting, "LSTM" or "lstm" will both be valid values that will be resolved to `NeuralNetwork.lstm`.1436+ """1437+ ),1438+ ] = True,1439 # Numbers408- min: Optional[Union[int, float]] = None,409- max: Optional[Union[int, float]] = None,410- clamp: bool = False,1440+ min: Annotated[1441+ Optional[Union[int, float]],1442+ Doc(1443+ """1444+ For a CLI Argument representing a [number](https://typer.tiangolo.com/tutorial/parameter-types/number/) (`int` or `float`),1445+ you can define numeric validations with `min` and `max` values:1446+1447+ **Example**1448+1449+ ```python1450+ @app.command()1451+ def main(1452+ user: Annotated[str, typer.Argument()],1453+ user_id: Annotated[int, typer.Argument(min=1, max=1000)],1454+ ):1455+ print(f"ID for {user} is {user_id}")1456+ ```1457+1458+ If the user attempts to input an invalid number, an error will be shown, explaining why the value is invalid.1459+ """1460+ ),1461+ ] = None,1462+ max: Annotated[1463+ Optional[Union[int, float]],1464+ Doc(1465+ """1466+ For a CLI Argument representing a [number](https://typer.tiangolo.com/tutorial/parameter-types/number/) (`int` or `float`),1467+ you can define numeric validations with `min` and `max` values:1468+1469+ **Example**1470+1471+ ```python1472+ @app.command()1473+ def main(1474+ user: Annotated[str, typer.Argument()],1475+ user_id: Annotated[int, typer.Argument(min=1, max=1000)],1476+ ):1477+ print(f"ID for {user} is {user_id}")1478+ ```1479+1480+ If the user attempts to input an invalid number, an error will be shown, explaining why the value is invalid.1481+ """1482+ ),1483+ ] = None,1484+ clamp: Annotated[1485+ bool,1486+ Doc(1487+ """1488+ For a CLI Argument representing a [number](https://typer.tiangolo.com/tutorial/parameter-types/number/) and that is bounded by using `min` and/or `max`,1489+ you can opt to use the closest minimum or maximum value instead of raising an error. This is done by setting `clamp` to `True`.1490+1491+ **Example**1492+1493+ ```python1494+ @app.command()1495+ def main(1496+ user: Annotated[str, typer.Argument()],1497+ user_id: Annotated[int, typer.Argument(min=1, max=1000, clamp=True)],1498+ ):1499+ print(f"ID for {user} is {user_id}")1500+ ```1501+1502+ If the user attempts to input 3420 for `user_id`, this will internally be converted to `1000`.1503+ """1504+ ),1505+ ] = False,1506 # DateTime412- formats: Optional[list[str]] = None,1507+ formats: Annotated[1508+ Optional[list[str]],1509+ Doc(1510+ """1511+ For a CLI Argument representing a [DateTime object](https://typer.tiangolo.com/tutorial/parameter-types/datetime),1512+ you can customize the formats that can be parsed automatically:1513+1514+ **Example**1515+1516+ ```python1517+ from datetime import datetime1518+1519+ @app.command()1520+ def main(1521+ birthday: Annotated[1522+ datetime,1523+ typer.Argument(1524+ formats=["%Y-%m-%d", "%Y-%m-%d %H:%M:%S", "%m/%d/%Y"]1525+ ),1526+ ],1527+ ):1528+ print(f"Birthday defined at: {birthday}")1529+ ```1530+ """1531+ ),1532+ ] = None,1533 # File414- mode: Optional[str] = None,415- encoding: Optional[str] = None,416- errors: Optional[str] = "strict",417- lazy: Optional[bool] = None,418- atomic: bool = False,1534+ mode: Annotated[1535+ Optional[str],1536+ Doc(1537+ """1538+ For a CLI Argument representing a [File object](https://typer.tiangolo.com/tutorial/parameter-types/file/),1539+ you can customize the mode to open the file with. If unset, Typer will set a [sensible value by default](https://typer.tiangolo.com/tutorial/parameter-types/file/#advanced-mode).1540+1541+ **Example**1542+1543+ ```python1544+ @app.command()1545+ def main(config: Annotated[typer.FileText, typer.Argument(mode="a")]):1546+ config.write("This is a single line\\n")1547+ print("Config line written")1548+ ```1549+ """1550+ ),1551+ ] = None,1552+ encoding: Annotated[1553+ Optional[str],1554+ Doc(1555+ """1556+ Customize the encoding of this CLI Argument represented by a [File object](https://typer.tiangolo.com/tutorial/parameter-types/file/).1557+1558+ **Example**1559+1560+ ```python1561+ @app.command()1562+ def main(config: Annotated[typer.FileText, typer.Argument(encoding="utf-8")]):1563+ config.write("All the text gets written\\n")1564+ ```1565+ """1566+ ),1567+ ] = None,1568+ errors: Annotated[1569+ Optional[str],1570+ Doc(1571+ """1572+ **Note**: you probably shouldn't use this parameter, it is inherited from Click and supported for compatibility.1573+1574+ ---1575+1576+ The error handling mode.1577+ """1578+ ),1579+ ] = "strict",1580+ lazy: Annotated[1581+ Optional[bool],1582+ Doc(1583+ """1584+ For a CLI Argument representing a [File object](https://typer.tiangolo.com/tutorial/parameter-types/file/),1585+ by default the file will not be created until you actually start writing to it.1586+ You can change this behaviour by setting this parameter.1587+ By default, it's set to `True` for writing and to `False` for reading.1588+1589+ **Example**1590+1591+ ```python1592+ @app.command()1593+ def main(config: Annotated[typer.FileText, typer.Argument(mode="a", lazy=False)]):1594+ config.write("This is a single line\\n")1595+ print("Config line written")1596+ ```1597+ """1598+ ),1599+ ] = None,1600+ atomic: Annotated[1601+ bool,1602+ Doc(1603+ """1604+ For a CLI Argument representing a [File object](https://typer.tiangolo.com/tutorial/parameter-types/file/),1605+ you can ensure that all write instructions first go into a temporal file, and are only moved to the final destination after completing1606+ by setting `atomic` to `True`. This can be useful for files with potential concurrent access.1607+1608+ **Example**1609+1610+ ```python1611+ @app.command()1612+ def main(config: Annotated[typer.FileText, typer.Argument(mode="a", atomic=True)]):1613+ config.write("All the text")1614+ ```1615+ """1616+ ),1617+ ] = False,1618 # Path420- exists: bool = False,421- file_okay: bool = True,422- dir_okay: bool = True,423- writable: bool = False,424- readable: bool = True,425- resolve_path: bool = False,426- allow_dash: bool = False,427- path_type: Union[None, type[str], type[bytes]] = None,1619+ exists: Annotated[1620+ bool,1621+ Doc(1622+ """1623+ When set to `True` for a [`Path` argument](https://typer.tiangolo.com/tutorial/parameter-types/path/),1624+ additional validation is performed to check that the file or directory exists. If not, the value will be invalid.1625+1626+ **Example**1627+1628+ ```python1629+ from pathlib import Path1630+1631+ @app.command()1632+ def main(config: Annotated[Path, typer.Argument(exists=True)]):1633+ text = config.read_text()1634+ print(f"Config file contents: {text}")1635+ ```1636+ """1637+ ),1638+ ] = False,1639+ file_okay: Annotated[1640+ bool,1641+ Doc(1642+ """1643+ Determine whether or not a [`Path` argument](https://typer.tiangolo.com/tutorial/parameter-types/path/)1644+ is allowed to refer to a file. When this is set to `False`, the application will raise a validation error when a path to a file is given.1645+1646+ **Example**1647+1648+ ```python1649+ from pathlib import Path1650+1651+ @app.command()1652+ def main(config: Annotated[Path, typer.Argument(exists=True, file_okay=False)]):1653+ print(f"Directory listing: {[x.name for x in config.iterdir()]}")1654+ ```1655+ """1656+ ),1657+ ] = True,1658+ dir_okay: Annotated[1659+ bool,1660+ Doc(1661+ """1662+ Determine whether or not a [`Path` argument](https://typer.tiangolo.com/tutorial/parameter-types/path/)1663+ is allowed to refer to a directory. When this is set to `False`, the application will raise a validation error when a path to a directory is given.1664+1665+ **Example**1666+1667+ ```python1668+ from pathlib import Path1669+1670+ @app.command()1671+ def main(config: Annotated[Path, typer.Argument(exists=True, dir_okay=False)]):1672+ text = config.read_text()1673+ print(f"Config file contents: {text}")1674+ ```1675+ """1676+ ),1677+ ] = True,1678+ writable: Annotated[1679+ bool,1680+ Doc(1681+ """1682+ Whether or not to perform a writable check for this [`Path` argument](https://typer.tiangolo.com/tutorial/parameter-types/path/).1683+1684+ **Example**1685+1686+ ```python1687+ from pathlib import Path1688+1689+ @app.command()1690+ def main(config: Annotated[Path, typer.Argument(writable=True)]):1691+ config.write_text("All the text")1692+ ```1693+ """1694+ ),1695+ ] = False,1696+ readable: Annotated[1697+ bool,1698+ Doc(1699+ """1700+ Whether or not to perform a readable check for this [`Path` argument](https://typer.tiangolo.com/tutorial/parameter-types/path/).1701+1702+ **Example**1703+1704+ ```python1705+ from pathlib import Path1706+1707+ @app.command()1708+ def main(config: Annotated[Path, typer.Argument(readable=True)]):1709+ config.read_text("All the text")1710+ ```1711+ """1712+ ),1713+ ] = True,1714+ resolve_path: Annotated[1715+ bool,1716+ Doc(1717+ """1718+ Whether or not to fully resolve the path of this [`Path` argument](https://typer.tiangolo.com/tutorial/parameter-types/path/),1719+ meaning that the path becomes absolute and symlinks are resolved.1720+1721+ **Example**1722+1723+ ```python1724+ from pathlib import Path1725+1726+ @app.command()1727+ def main(config: Annotated[Path, typer.Argument(resolve_path=True)]):1728+ config.read_text("All the text")1729+ ```1730+ """1731+ ),1732+ ] = False,1733+ allow_dash: Annotated[1734+ bool,1735+ Doc(1736+ """1737+ When set to `True`, a single dash for this [`Path` argument](https://typer.tiangolo.com/tutorial/parameter-types/path/)1738+ would be a valid value, indicating standard streams. This is a more advanced use-case.1739+ """1740+ ),1741+ ] = False,1742+ path_type: Annotated[1743+ Union[None, type[str], type[bytes]],1744+ Doc(1745+ """1746+ A string type that will be used to represent this [`Path` argument](https://typer.tiangolo.com/tutorial/parameter-types/path/).1747+ The default is `None` which means the return value will be either bytes or unicode, depending on what makes most sense given the input data.1748+ This is a more advanced use-case.1749+ """1750+ ),1751+ ] = None,1752 # Rich settings429- rich_help_panel: Union[str, None] = None,1753+ rich_help_panel: Annotated[1754+ Union[str, None],1755+ Doc(1756+ """1757+ Set the panel name where you want this CLI Argument to be shown in the [help text](https://typer.tiangolo.com/tutorial/arguments/help).1758+1759+ **Example**1760+1761+ ```python1762+ @app.command()1763+ def main(1764+ name: Annotated[str, typer.Argument(help="Who to greet")],1765+ age: Annotated[str, typer.Option(help="Their age", rich_help_panel="Data")],1766+ ):1767+ print(f"Hello {name} of age {age}")1768+ ```1769+ """1770+ ),1771+ ] = None,1772 ) -> Any:1773+ """1774+ A [CLI Argument](https://typer.tiangolo.com/tutorial/arguments) is a positional parameter to your command line application.1775+1776+ Often, CLI Arguments are required, meaning that users have to specify them. However, you can set them to be optional by defining a default value:1777+1778+ ## Example1779+1780+ ```python1781+ @app.command()1782+ def main(name: Annotated[str, typer.Argument()] = "World"):1783+ print(f"Hello {name}!")1784+ ```1785+1786+ Note how in this example, if `name` is not specified on the command line, the application will still execute normally and print "Hello World!".1787+ """1788 return ArgumentInfo(1789 # Parameter1790 default=default,1791 # Arguments can only have one param declaration45 unmodified linesmodified:mkdocs.yml+26 added
65 unmodified lines66 - members: data/members.yml67 redirects:68 redirect_maps:69 typer-cli.md: tutorial/typer-command.md70+ mkdocstrings:71+ handlers:72+ python:73+ options:74+ extensions:75+ - griffe_typingdoc76+ show_root_heading: true77+ show_if_no_docstring: true78+ inherited_members: true79+ members_order: source80+ separate_signature: true81+ unwrap_annotated: true82+ filters:83+ - '!^_'84+ merge_init_into_class: true85+ docstring_section_style: spacy86+ signature_crossrefs: true87+ show_symbol_type_heading: true88+ show_symbol_type_toc: true89 90 nav:91 - Typer: index.md92 - features.md63 unmodified lines156 - tutorial/package.md157 - tutorial/exceptions.md158 - tutorial/one-file-per-command.md159 - tutorial/typer-command.md160+ - Reference (Code API):161+ - reference/index.md162+ - reference/typer.md163+ - reference/run_launch.md164+ - reference/parameters.md165+ - reference/file_objects.md166+ - reference/context.md167 - Resources:168 - resources/index.md169 - help-typer.md170 - contributing.md85 unmodified linesmodified:pyproject.toml+1 added
33 unmodified lines34 "Programming Language :: Python :: 3.14",35 ]36 dependencies = [37 "click >= 8.0.0",38+ "annotated-doc >=0.0.2",39 ]40 readme = "README.md"41 42 [project.urls]217 unmodified linesmodified:uv.lock+11 added
5 unmodified lines6 "python_full_version < '3.10'",7 ]8 9 [[package]]10+name = "annotated-doc"11+version = "0.0.4"12+source = { registry = "https://pypi.org/simple" }13+sdist = { url = "https://files.pythonhosted.org/packages/57/ba/046ceea27344560984e26a590f90bc7f4a75b06701f653222458922b558c/annotated_doc-0.0.4.tar.gz", hash = "sha256:fbcda96e87e9c92ad167c2e53839e57503ecfda18804ea28102353485033faa4", size = 7288, upload-time = "2025-11-10T22:07:42.062Z" }14+wheels = [15+ { url = "https://files.pythonhosted.org/packages/1e/d3/26bf1008eb3d2daa8ef4cacc7f3bfdc11818d111f7e2d0201bc6e3b49d45/annotated_doc-0.0.4-py3-none-any.whl", hash = "sha256:571ac1dc6991c450b25a9c2d84a3705e2ae7a53467b5d111c24fa8baabbed320", size = 5303, upload-time = "2025-11-10T22:07:40.673Z" },16+]17+18+[[package]]19 name = "annotated-types"20 version = "0.7.0"21 source = { registry = "https://pypi.org/simple" }22 sdist = { url = "https://files.pythonhosted.org/packages/ee/67/531ea369ba64dcff5ec9c3402f9f51bf748cec26dde048a2f973a4eea7f5/annotated_types-0.7.0.tar.gz", hash = "sha256:aff07c09a53a08bc8cfccb9c85b05f1aa9a2a6f23728d790723543408344ce89", size = 16081, upload-time = "2024-05-20T21:33:25.928Z" }2442 unmodified lines2465 [[package]]2466 name = "typer"2467 source = { editable = "." }2468 dependencies = [2469+ { name = "annotated-doc" },2470 { name = "click", version = "8.1.8", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.10'" },2471 { name = "click", version = "8.3.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.10'" },2472 { name = "rich" },2473 { name = "shellingham" },67 unmodified lines2541 ]2542 2543 [package.metadata]2544 requires-dist = [2545+ { name = "annotated-doc", specifier = ">=0.0.2" },2546 { name = "click", specifier = ">=8.0.0" },2547 { name = "rich", specifier = ">=10.11.0" },2548 { name = "shellingham", specifier = ">=1.3.0" },2549 ]143 unmodified lines