Coverage for typer / main.py: 100%
393 statements
« prev ^ index » next coverage.py v7.13.1, created at 2026-11-18 11:12 +0000
« prev ^ index » next coverage.py v7.13.1, created at 2026-11-18 11:12 +0000
1import inspect 1abcdefghij
2import os 1abcdefghij
3import platform 1abcdefghij
4import shutil 1abcdefghij
5import subprocess 1abcdefghij
6import sys 1abcdefghij
7import traceback 1abcdefghij
8from collections.abc import Callable, Sequence 1abcdefghij
9from functools import update_wrapper 1abcdefghij
10from traceback import FrameSummary, StackSummary 1abcdefghij
11from types import TracebackType 1abcdefghij
12from typing import Annotated, Any 1abcdefghij
14from annotated_doc import Doc 1abcdefghij
16from . import _click 1abcdefghij
17from ._click.globals import get_current_context 1abcdefghij
18from ._coercion import resolve_type_descriptor 1abcdefghij
19from ._param_types import lenient_issubclass, parse_param_annotation 1abcdefghij
20from ._typing import get_args, get_origin 1abcdefghij
21from .completion import get_completion_inspect_parameters 1abcdefghij
22from .core import ( 1abcdefghij
23 DEFAULT_MARKUP_MODE,
24 HAS_RICH,
25 MarkupMode,
26 TyperArgument,
27 TyperCommand,
28 TyperGroup,
29 TyperOption,
30)
31from .models import ( 1abcdefghij
32 ArgumentInfo,
33 CommandFunctionType,
34 CommandInfo,
35 Default,
36 DefaultPlaceholder,
37 DeveloperExceptionConfig,
38 OptionInfo,
39 ParameterInfo,
40 ParamMeta,
41 Required,
42 TyperInfo,
43)
44from .utils import get_params_from_function 1abcdefghij
46_original_except_hook = sys.excepthook 1abcdefghij
47_typer_developer_exception_attr_name = "__typer_developer_exception__" 1abcdefghij
50def except_hook( 1abcdefghij
51 exc_type: type[BaseException], exc_value: BaseException, tb: TracebackType | None
52) -> None:
53 exception_config: DeveloperExceptionConfig | None = getattr( 1abcdefghij
54 exc_value, _typer_developer_exception_attr_name, None
55 )
56 standard_traceback = os.getenv( 1abcdefghij
57 "TYPER_STANDARD_TRACEBACK", os.getenv("_TYPER_STANDARD_TRACEBACK")
58 )
59 if ( 1a
60 standard_traceback
61 or not exception_config
62 or not exception_config.pretty_exceptions_enable
63 ):
64 _original_except_hook(exc_type, exc_value, tb) 1abcdefghij
65 return 1abcdefghij
66 typer_path = os.path.dirname(__file__) 1abcdefghij
67 click_path = os.path.dirname(_click.__file__) 1abcdefghij
68 internal_dir_names = [typer_path, click_path] 1abcdefghij
69 exc = exc_value 1abcdefghij
70 if HAS_RICH: 1abcdefghij
71 from . import rich_utils 1abcdefghij
73 rich_tb = rich_utils.get_traceback(exc, exception_config, internal_dir_names) 1abcdefghij
74 console_stderr = rich_utils._get_rich_console(stderr=True) 1abcdefghij
75 console_stderr.print(rich_tb) 1abcdefghij
76 return 1abcdefghij
77 tb_exc = traceback.TracebackException.from_exception(exc) 1abcdefghij
78 stack: list[FrameSummary] = [] 1abcdefghij
79 for frame in tb_exc.stack: 1abcdefghij
80 if any(frame.filename.startswith(path) for path in internal_dir_names): 1abcdefghij
81 if not exception_config.pretty_exceptions_short: 1abcdefghij
82 # Hide the line for internal libraries, Typer and Click
83 stack.append( 1abcdefghij
84 traceback.FrameSummary(
85 filename=frame.filename,
86 lineno=frame.lineno,
87 name=frame.name,
88 line="",
89 )
90 )
91 else:
92 stack.append(frame) 1abcdefghij
93 # Type ignore ref: https://github.com/python/typeshed/pull/8244
94 final_stack_summary = StackSummary.from_list(stack) 1abcdefghij
95 tb_exc.stack = final_stack_summary 1abcdefghij
96 for line in tb_exc.format(): 1abcdefghij
97 print(line, file=sys.stderr) 1abcdefghij
98 return 1abcdefghij
101def get_install_completion_arguments() -> tuple[_click.Parameter, _click.Parameter]: 1abcdefghij
102 install_param, show_param = get_completion_inspect_parameters() 1abcdefghij
103 click_install_param = _get_param(install_param) 1abcdefghij
104 click_show_param = _get_param(show_param) 1abcdefghij
105 return click_install_param, click_show_param 1abcdefghij
108class Typer: 1abcdefghij
109 """
110 `Typer` main class, the main entrypoint to use Typer.
112 Read more in the
113 [Typer docs for First Steps](https://typer.tiangolo.com/tutorial/typer-app/).
115 ## Example
117 ```python
118 import typer
120 app = typer.Typer()
121 ```
122 """
124 def __init__( 1abcdefghij
125 self,
126 *,
127 name: Annotated[
128 str | None,
129 Doc(
130 """
131 The name of this application.
132 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=...)`.
134 **Example**
136 ```python
137 import typer
139 app = typer.Typer(name="users")
140 ```
141 """
142 ),
143 ] = Default(None),
144 cls: Annotated[
145 type[TyperGroup] | None,
146 Doc(
147 """
148 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`.
149 Otherwise, should be a subtype of `TyperGroup`.
151 **Example**
153 ```python
154 import typer
156 app = typer.Typer(cls=TyperGroup)
157 ```
158 """
159 ),
160 ] = Default(None),
161 invoke_without_command: Annotated[
162 bool,
163 Doc(
164 """
165 By setting this to `True`, you can make sure a callback is executed even when no subcommand is provided.
167 **Example**
169 ```python
170 import typer
172 app = typer.Typer(invoke_without_command=True)
173 ```
174 """
175 ),
176 ] = Default(False),
177 no_args_is_help: Annotated[
178 bool,
179 Doc(
180 """
181 If this is set to `True`, running a command without any arguments will automatically show the help page.
183 **Example**
185 ```python
186 import typer
188 app = typer.Typer(no_args_is_help=True)
189 ```
190 """
191 ),
192 ] = Default(False),
193 subcommand_metavar: Annotated[
194 str | None,
195 Doc(
196 """
197 **Note**: you probably shouldn't use this parameter, it is inherited
198 from Click and supported for compatibility.
200 ---
202 How to represent the subcommand argument in help.
203 """
204 ),
205 ] = Default(None),
206 chain: Annotated[
207 bool,
208 Doc(
209 """
210 **Note**: you probably shouldn't use this parameter, it is inherited
211 from Click and supported for compatibility.
213 ---
215 Allow passing more than one subcommand argument.
216 """
217 ),
218 ] = Default(False),
219 result_callback: Annotated[
220 Callable[..., Any] | None,
221 Doc(
222 """
223 **Note**: you probably shouldn't use this parameter, it is inherited
224 from Click and supported for compatibility.
226 ---
228 A function to call after the group's and subcommand's callbacks.
229 """
230 ),
231 ] = Default(None),
232 # Command
233 context_settings: Annotated[
234 dict[Any, Any] | None,
235 Doc(
236 """
237 Pass configurations for the [context](https://typer.tiangolo.com/tutorial/commands/context/).
238 Available configurations can be found in the docs for Click's `Context` [here](https://click.palletsprojects.com/en/stable/api/#context).
240 **Example**
242 ```python
243 import typer
245 app = typer.Typer(context_settings={"help_option_names": ["-h", "--help"]})
246 ```
247 """
248 ),
249 ] = Default(None),
250 callback: Annotated[
251 Callable[..., Any] | None,
252 Doc(
253 """
254 Add a callback to the main Typer app. Can be overridden with `@app.callback()`.
255 See [the tutorial about callbacks](https://typer.tiangolo.com/tutorial/commands/callback/) for more details.
257 **Example**
259 ```python
260 import typer
262 def callback():
263 print("Running a command")
265 app = typer.Typer(callback=callback)
266 ```
267 """
268 ),
269 ] = Default(None),
270 help: Annotated[
271 str | None,
272 Doc(
273 """
274 Help text for the main Typer app.
275 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,
276 and which one takes priority.
278 **Example**
280 ```python
281 import typer
283 app = typer.Typer(help="Some help.")
284 ```
285 """
286 ),
287 ] = Default(None),
288 epilog: Annotated[
289 str | None,
290 Doc(
291 """
292 Text that will be printed right after the help text.
294 **Example**
296 ```python
297 import typer
299 app = typer.Typer(epilog="May the force be with you")
300 ```
301 """
302 ),
303 ] = Default(None),
304 short_help: Annotated[
305 str | None,
306 Doc(
307 """
308 A shortened version of the help text that can be used e.g. in the help table listing subcommands.
309 When not defined, the normal `help` text will be used instead.
311 **Example**
313 ```python
314 import typer
316 app = typer.Typer(help="A lot of explanation about user management", short_help="user management")
317 ```
318 """
319 ),
320 ] = Default(None),
321 options_metavar: Annotated[
322 str,
323 Doc(
324 """
325 In the example usage string of the help text for a command, the default placeholder for various arguments is `[OPTIONS]`.
326 Set `options_metavar` to change this into a different string.
328 **Example**
330 ```python
331 import typer
333 app = typer.Typer(options_metavar="[OPTS]")
334 ```
335 """
336 ),
337 ] = Default("[OPTIONS]"),
338 add_help_option: Annotated[
339 bool,
340 Doc(
341 """
342 **Note**: you probably shouldn't use this parameter, it is inherited
343 from Click and supported for compatibility.
345 ---
347 By default each command registers a `--help` option. This can be disabled by this parameter.
348 """
349 ),
350 ] = Default(True),
351 hidden: Annotated[
352 bool,
353 Doc(
354 """
355 Hide this command from help outputs. `False` by default.
357 **Example**
359 ```python
360 import typer
362 app = typer.Typer(hidden=True)
363 ```
364 """
365 ),
366 ] = Default(False),
367 deprecated: Annotated[
368 bool,
369 Doc(
370 """
371 Mark this command as being deprecated in the help text. `False` by default.
373 **Example**
375 ```python
376 import typer
378 app = typer.Typer(deprecated=True)
379 ```
380 """
381 ),
382 ] = Default(False),
383 add_completion: Annotated[
384 bool,
385 Doc(
386 """
387 Toggle whether or not to add the `--install-completion` and `--show-completion` options to the app.
388 Set to `True` by default.
390 **Example**
392 ```python
393 import typer
395 app = typer.Typer(add_completion=False)
396 ```
397 """
398 ),
399 ] = True,
400 # Rich settings
401 rich_markup_mode: Annotated[
402 MarkupMode,
403 Doc(
404 """
405 Enable markup text if you have Rich installed. This can be set to `"markdown"`, `"rich"`, or `None`.
406 By default, `rich_markup_mode` is `None` if Rich is not installed, and `"rich"` if it is installed.
407 See [the tutorial on help formatting](https://typer.tiangolo.com/tutorial/commands/help/#rich-markdown-and-markup) for more information.
409 **Example**
411 ```python
412 import typer
414 app = typer.Typer(rich_markup_mode="rich")
415 ```
416 """
417 ),
418 ] = DEFAULT_MARKUP_MODE,
419 rich_help_panel: Annotated[
420 str | None,
421 Doc(
422 """
423 Set the panel name of the command when the help is printed with Rich.
425 **Example**
427 ```python
428 import typer
430 app = typer.Typer(rich_help_panel="Utils and Configs")
431 ```
432 """
433 ),
434 ] = Default(None),
435 suggest_commands: Annotated[
436 bool,
437 Doc(
438 """
439 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.
440 You can turn this setting off with `suggest_commands`:
442 **Example**
444 ```python
445 import typer
447 app = typer.Typer(suggest_commands=False)
448 ```
449 """
450 ),
451 ] = True,
452 pretty_exceptions_enable: Annotated[
453 bool,
454 Doc(
455 """
456 If you want to disable [pretty exceptions with Rich](https://typer.tiangolo.com/tutorial/exceptions/#exceptions-with-rich),
457 you can set `pretty_exceptions_enable` to `False`. When doing so, you will see the usual standard exception trace.
459 **Example**
461 ```python
462 import typer
464 app = typer.Typer(pretty_exceptions_enable=False)
465 ```
466 """
467 ),
468 ] = True,
469 pretty_exceptions_show_locals: Annotated[
470 bool,
471 Doc(
472 """
473 If Rich is installed, [error messages](https://typer.tiangolo.com/tutorial/exceptions/#exceptions-and-errors)
474 will be nicely printed.
476 If you set `pretty_exceptions_show_locals=True` it will also include the values of local variables for easy debugging.
478 However, if such a variable contains delicate information, you should consider leaving `pretty_exceptions_show_locals=False`
479 (the default) to `False` to enhance security.
481 **Example**
483 ```python
484 import typer
486 app = typer.Typer(pretty_exceptions_show_locals=True)
487 ```
488 """
489 ),
490 ] = False,
491 pretty_exceptions_short: Annotated[
492 bool,
493 Doc(
494 """
495 By default, [pretty exceptions formatted with Rich](https://typer.tiangolo.com/tutorial/exceptions/#exceptions-with-rich) hide the long stack trace.
496 If you want to show the full trace instead, you can set the parameter `pretty_exceptions_short` to `False`:
498 **Example**
500 ```python
501 import typer
503 app = typer.Typer(pretty_exceptions_short=False)
504 ```
505 """
506 ),
507 ] = True,
508 ):
509 self._add_completion = add_completion 1abcdefghij
510 self.rich_markup_mode: MarkupMode = rich_markup_mode 1abcdefghij
511 self.rich_help_panel = rich_help_panel 1abcdefghij
512 self.suggest_commands = suggest_commands 1abcdefghij
513 self.pretty_exceptions_enable = pretty_exceptions_enable 1abcdefghij
514 self.pretty_exceptions_show_locals = pretty_exceptions_show_locals 1abcdefghij
515 self.pretty_exceptions_short = pretty_exceptions_short 1abcdefghij
516 self.info = TyperInfo( 1abcdefghij
517 name=name,
518 cls=cls,
519 invoke_without_command=invoke_without_command,
520 no_args_is_help=no_args_is_help,
521 subcommand_metavar=subcommand_metavar,
522 chain=chain,
523 result_callback=result_callback,
524 context_settings=context_settings,
525 callback=callback,
526 help=help,
527 epilog=epilog,
528 short_help=short_help,
529 options_metavar=options_metavar,
530 add_help_option=add_help_option,
531 hidden=hidden,
532 deprecated=deprecated,
533 )
534 self.registered_groups: list[TyperInfo] = [] 1abcdefghij
535 self.registered_commands: list[CommandInfo] = [] 1abcdefghij
536 self.registered_callback: TyperInfo | None = None 1abcdefghij
538 def callback( 1abcdefghij
539 self,
540 *,
541 cls: Annotated[
542 type[TyperGroup] | None,
543 Doc(
544 """
545 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`.
546 Otherwise, should be a subtype of `TyperGroup`.
547 """
548 ),
549 ] = Default(None),
550 invoke_without_command: Annotated[
551 bool,
552 Doc(
553 """
554 By setting this to `True`, you can make sure a callback is executed even when no subcommand is provided.
555 """
556 ),
557 ] = Default(False),
558 no_args_is_help: Annotated[
559 bool,
560 Doc(
561 """
562 If this is set to `True`, running a command without any arguments will automatically show the help page.
563 """
564 ),
565 ] = Default(False),
566 subcommand_metavar: Annotated[
567 str | None,
568 Doc(
569 """
570 **Note**: you probably shouldn't use this parameter, it is inherited
571 from Click and supported for compatibility.
573 ---
575 How to represent the subcommand argument in help.
576 """
577 ),
578 ] = Default(None),
579 chain: Annotated[
580 bool,
581 Doc(
582 """
583 **Note**: you probably shouldn't use this parameter, it is inherited
584 from Click and supported for compatibility.
586 ---
588 Allow passing more than one subcommand argument.
589 """
590 ),
591 ] = Default(False),
592 result_callback: Annotated[
593 Callable[..., Any] | None,
594 Doc(
595 """
596 **Note**: you probably shouldn't use this parameter, it is inherited
597 from Click and supported for compatibility.
599 ---
601 A function to call after the group's and subcommand's callbacks.
602 """
603 ),
604 ] = Default(None),
605 # Command
606 context_settings: Annotated[
607 dict[Any, Any] | None,
608 Doc(
609 """
610 Pass configurations for the [context](https://typer.tiangolo.com/tutorial/commands/context/).
611 Available configurations can be found in the docs for Click's `Context` [here](https://click.palletsprojects.com/en/stable/api/#context).
612 """
613 ),
614 ] = Default(None),
615 help: Annotated[
616 str | None,
617 Doc(
618 """
619 Help text for the command.
620 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,
621 and which one takes priority.
622 """
623 ),
624 ] = Default(None),
625 epilog: Annotated[
626 str | None,
627 Doc(
628 """
629 Text that will be printed right after the help text.
630 """
631 ),
632 ] = Default(None),
633 short_help: Annotated[
634 str | None,
635 Doc(
636 """
637 A shortened version of the help text that can be used e.g. in the help table listing subcommands.
638 When not defined, the normal `help` text will be used instead.
639 """
640 ),
641 ] = Default(None),
642 options_metavar: Annotated[
643 str | None,
644 Doc(
645 """
646 In the example usage string of the help text for a command, the default placeholder for various arguments is `[OPTIONS]`.
647 Set `options_metavar` to change this into a different string. When `None`, the default value will be used.
648 """
649 ),
650 ] = Default(None),
651 add_help_option: Annotated[
652 bool,
653 Doc(
654 """
655 **Note**: you probably shouldn't use this parameter, it is inherited
656 from Click and supported for compatibility.
658 ---
660 By default each command registers a `--help` option. This can be disabled by this parameter.
661 """
662 ),
663 ] = Default(True),
664 hidden: Annotated[
665 bool,
666 Doc(
667 """
668 Hide this command from help outputs. `False` by default.
669 """
670 ),
671 ] = Default(False),
672 deprecated: Annotated[
673 bool,
674 Doc(
675 """
676 Mark this command as deprecated in the help text. `False` by default.
677 """
678 ),
679 ] = Default(False),
680 # Rich settings
681 rich_help_panel: Annotated[
682 str | None,
683 Doc(
684 """
685 Set the panel name of the command when the help is printed with Rich.
686 """
687 ),
688 ] = Default(None),
689 ) -> Callable[[CommandFunctionType], CommandFunctionType]:
690 """
691 Using the decorator `@app.callback`, you can declare the CLI parameters for the main CLI application.
693 Read more in the
694 [Typer docs for Callbacks](https://typer.tiangolo.com/tutorial/commands/callback/).
696 ## Example
698 ```python
699 import typer
701 app = typer.Typer()
702 state = {"verbose": False}
704 @app.callback()
705 def main(verbose: bool = False):
706 if verbose:
707 print("Will write verbose output")
708 state["verbose"] = True
710 @app.command()
711 def delete(username: str):
712 # define subcommand
713 ...
714 ```
715 """
717 def decorator(f: CommandFunctionType) -> CommandFunctionType: 1abcdefghij
718 self.registered_callback = TyperInfo( 1abcdefghij
719 cls=cls,
720 invoke_without_command=invoke_without_command,
721 no_args_is_help=no_args_is_help,
722 subcommand_metavar=subcommand_metavar,
723 chain=chain,
724 result_callback=result_callback,
725 context_settings=context_settings,
726 callback=f,
727 help=help,
728 epilog=epilog,
729 short_help=short_help,
730 options_metavar=(
731 options_metavar or self._info_val_str("options_metavar")
732 ),
733 add_help_option=add_help_option,
734 hidden=hidden,
735 deprecated=deprecated,
736 rich_help_panel=rich_help_panel,
737 )
738 return f 1abcdefghij
740 return decorator 1abcdefghij
742 def command( 1abcdefghij
743 self,
744 name: Annotated[
745 str | None,
746 Doc(
747 """
748 The name of this command.
749 """
750 ),
751 ] = None,
752 *,
753 cls: Annotated[
754 type[TyperCommand] | None,
755 Doc(
756 """
757 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`.
758 Otherwise, should be a subtype of `TyperCommand`.
759 """
760 ),
761 ] = None,
762 context_settings: Annotated[
763 dict[Any, Any] | None,
764 Doc(
765 """
766 Pass configurations for the [context](https://typer.tiangolo.com/tutorial/commands/context/).
767 Available configurations can be found in the docs for Click's `Context` [here](https://click.palletsprojects.com/en/stable/api/#context).
768 """
769 ),
770 ] = None,
771 help: Annotated[
772 str | None,
773 Doc(
774 """
775 Help text for the command.
776 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,
777 and which one takes priority.
778 """
779 ),
780 ] = None,
781 epilog: Annotated[
782 str | None,
783 Doc(
784 """
785 Text that will be printed right after the help text.
786 """
787 ),
788 ] = None,
789 short_help: Annotated[
790 str | None,
791 Doc(
792 """
793 A shortened version of the help text that can be used e.g. in the help table listing subcommands.
794 When not defined, the normal `help` text will be used instead.
795 """
796 ),
797 ] = None,
798 options_metavar: Annotated[
799 str | None,
800 Doc(
801 """
802 In the example usage string of the help text for a command, the default placeholder for various arguments is `[OPTIONS]`.
803 Set `options_metavar` to change this into a different string. When `None`, the default value will be used.
804 """
805 ),
806 ] = Default(None),
807 add_help_option: Annotated[
808 bool,
809 Doc(
810 """
811 **Note**: you probably shouldn't use this parameter, it is inherited
812 from Click and supported for compatibility.
814 ---
816 By default each command registers a `--help` option. This can be disabled by this parameter.
817 """
818 ),
819 ] = True,
820 no_args_is_help: Annotated[
821 bool,
822 Doc(
823 """
824 If this is set to `True`, running a command without any arguments will automatically show the help page.
825 """
826 ),
827 ] = False,
828 hidden: Annotated[
829 bool,
830 Doc(
831 """
832 Hide this command from help outputs. `False` by default.
833 """
834 ),
835 ] = False,
836 deprecated: Annotated[
837 bool,
838 Doc(
839 """
840 Mark this command as deprecated in the help outputs. `False` by default.
841 """
842 ),
843 ] = False,
844 # Rich settings
845 rich_help_panel: Annotated[
846 str | None,
847 Doc(
848 """
849 Set the panel name of the command when the help is printed with Rich.
850 """
851 ),
852 ] = Default(None),
853 ) -> Callable[[CommandFunctionType], CommandFunctionType]:
854 """
855 Using the decorator `@app.command`, you can define a subcommand of the previously defined Typer app.
857 Read more in the
858 [Typer docs for Commands](https://typer.tiangolo.com/tutorial/commands/).
860 ## Example
862 ```python
863 import typer
865 app = typer.Typer()
867 @app.command()
868 def create():
869 print("Creating user: Hiro Hamada")
871 @app.command()
872 def delete():
873 print("Deleting user: Hiro Hamada")
874 ```
875 """
876 if cls is None: 1abcdefghij
877 cls = TyperCommand 1abcdefghij
879 def decorator(f: CommandFunctionType) -> CommandFunctionType: 1abcdefghij
880 self.registered_commands.append( 1abcdefghij
881 CommandInfo(
882 name=name,
883 cls=cls,
884 context_settings=context_settings,
885 callback=f,
886 help=help,
887 epilog=epilog,
888 short_help=short_help,
889 options_metavar=(
890 options_metavar or self._info_val_str("options_metavar")
891 ),
892 add_help_option=add_help_option,
893 no_args_is_help=no_args_is_help,
894 hidden=hidden,
895 deprecated=deprecated,
896 # Rich settings
897 rich_help_panel=rich_help_panel,
898 )
899 )
900 return f 1abcdefghij
902 return decorator 1abcdefghij
904 def add_typer( 1abcdefghij
905 self,
906 typer_instance: "Typer",
907 *,
908 name: Annotated[
909 str | None,
910 Doc(
911 """
912 The name of this subcommand.
913 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,
914 and which one takes priority.
915 """
916 ),
917 ] = Default(None),
918 cls: Annotated[
919 type[TyperGroup] | None,
920 Doc(
921 """
922 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`.
923 Otherwise, should be a subtype of `TyperGroup`.
924 """
925 ),
926 ] = Default(None),
927 invoke_without_command: Annotated[
928 bool,
929 Doc(
930 """
931 By setting this to `True`, you can make sure a callback is executed even when no subcommand is provided.
932 """
933 ),
934 ] = Default(False),
935 no_args_is_help: Annotated[
936 bool,
937 Doc(
938 """
939 If this is set to `True`, running a command without any arguments will automatically show the help page.
940 """
941 ),
942 ] = Default(False),
943 subcommand_metavar: Annotated[
944 str | None,
945 Doc(
946 """
947 **Note**: you probably shouldn't use this parameter, it is inherited
948 from Click and supported for compatibility.
950 ---
952 How to represent the subcommand argument in help.
953 """
954 ),
955 ] = Default(None),
956 chain: Annotated[
957 bool,
958 Doc(
959 """
960 **Note**: you probably shouldn't use this parameter, it is inherited
961 from Click and supported for compatibility.
963 ---
965 Allow passing more than one subcommand argument.
966 """
967 ),
968 ] = Default(False),
969 result_callback: Annotated[
970 Callable[..., Any] | None,
971 Doc(
972 """
973 **Note**: you probably shouldn't use this parameter, it is inherited
974 from Click and supported for compatibility.
976 ---
978 A function to call after the group's and subcommand's callbacks.
979 """
980 ),
981 ] = Default(None),
982 # Command
983 context_settings: Annotated[
984 dict[Any, Any] | None,
985 Doc(
986 """
987 Pass configurations for the [context](https://typer.tiangolo.com/tutorial/commands/context/).
988 Available configurations can be found in the docs for Click's `Context` [here](https://click.palletsprojects.com/en/stable/api/#context).
989 """
990 ),
991 ] = Default(None),
992 callback: Annotated[
993 Callable[..., Any] | None,
994 Doc(
995 """
996 Add a callback to this app.
997 See [the tutorial about callbacks](https://typer.tiangolo.com/tutorial/commands/callback/) for more details.
998 """
999 ),
1000 ] = Default(None),
1001 help: Annotated[
1002 str | None,
1003 Doc(
1004 """
1005 Help text for the subcommand.
1006 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,
1007 and which one takes priority.
1008 """
1009 ),
1010 ] = Default(None),
1011 epilog: Annotated[
1012 str | None,
1013 Doc(
1014 """
1015 Text that will be printed right after the help text.
1016 """
1017 ),
1018 ] = Default(None),
1019 short_help: Annotated[
1020 str | None,
1021 Doc(
1022 """
1023 A shortened version of the help text that can be used e.g. in the help table listing subcommands.
1024 When not defined, the normal `help` text will be used instead.
1025 """
1026 ),
1027 ] = Default(None),
1028 options_metavar: Annotated[
1029 str | None,
1030 Doc(
1031 """
1032 In the example usage string of the help text for a command, the default placeholder for various arguments is `[OPTIONS]`.
1033 Set `options_metavar` to change this into a different string. When `None`, the default value will be used.
1034 """
1035 ),
1036 ] = Default(None),
1037 add_help_option: Annotated[
1038 bool,
1039 Doc(
1040 """
1041 **Note**: you probably shouldn't use this parameter, it is inherited
1042 from Click and supported for compatibility.
1044 ---
1046 By default each command registers a `--help` option. This can be disabled by this parameter.
1047 """
1048 ),
1049 ] = Default(True),
1050 hidden: Annotated[
1051 bool,
1052 Doc(
1053 """
1054 Hide this command from help outputs. `False` by default.
1055 """
1056 ),
1057 ] = Default(False),
1058 deprecated: Annotated[
1059 bool,
1060 Doc(
1061 """
1062 Mark this command as deprecated in the help outputs. `False` by default.
1063 """
1064 ),
1065 ] = False,
1066 # Rich settings
1067 rich_help_panel: Annotated[
1068 str | None,
1069 Doc(
1070 """
1071 Set the panel name of the command when the help is printed with Rich.
1072 """
1073 ),
1074 ] = Default(None),
1075 ) -> None:
1076 """
1077 Add subcommands to the main app using `app.add_typer()`.
1078 Subcommands may be defined in separate modules, ensuring clean separation of code by functionality.
1080 Read more in the
1081 [Typer docs for SubCommands](https://typer.tiangolo.com/tutorial/subcommands/add-typer/).
1083 ## Example
1085 ```python
1086 import typer
1088 from .add import app as add_app
1089 from .delete import app as delete_app
1091 app = typer.Typer()
1093 app.add_typer(add_app)
1094 app.add_typer(delete_app)
1095 ```
1096 """
1097 self.registered_groups.append( 1abcdefghij
1098 TyperInfo(
1099 typer_instance,
1100 name=name,
1101 cls=cls,
1102 invoke_without_command=invoke_without_command,
1103 no_args_is_help=no_args_is_help,
1104 subcommand_metavar=subcommand_metavar,
1105 chain=chain,
1106 result_callback=result_callback,
1107 context_settings=context_settings,
1108 callback=callback,
1109 help=help,
1110 epilog=epilog,
1111 short_help=short_help,
1112 options_metavar=(
1113 options_metavar or self._info_val_str("options_metavar")
1114 ),
1115 add_help_option=add_help_option,
1116 hidden=hidden,
1117 deprecated=deprecated,
1118 rich_help_panel=rich_help_panel,
1119 )
1120 )
1122 def __call__(self, *args: Any, **kwargs: Any) -> Any: 1abcdefghij
1123 if sys.excepthook != except_hook: 1abcdefghij
1124 sys.excepthook = except_hook 1abcdefghij
1125 try: 1abcdefghij
1126 return get_command(self)(*args, **kwargs) 1abcdefghij
1127 except Exception as e: 1abcdefghij
1128 # Set a custom attribute to tell the hook to show nice exceptions for user
1129 # code. An alternative/first implementation was a custom exception with
1130 # raise custom_exc from e
1131 # but that means the last error shown is the custom exception, not the
1132 # actual error. This trick improves developer experience by showing the
1133 # actual error last.
1134 setattr( 1abcdefghij
1135 e,
1136 _typer_developer_exception_attr_name,
1137 DeveloperExceptionConfig(
1138 pretty_exceptions_enable=self.pretty_exceptions_enable,
1139 pretty_exceptions_show_locals=self.pretty_exceptions_show_locals,
1140 pretty_exceptions_short=self.pretty_exceptions_short,
1141 ),
1142 )
1143 raise e 1abcdefghij
1145 def _info_val_str(self, name: str) -> str: 1abcdefghij
1146 val = getattr(self.info, name) 1abcdefghij
1147 val_str = val.value if isinstance(val, DefaultPlaceholder) else val 1abcdefghij
1148 assert isinstance(val_str, str) 1abcdefghij
1149 return val_str 1abcdefghij
1152def get_group(typer_instance: Typer) -> TyperGroup: 1abcdefghij
1153 group = get_group_from_info( 1abcdefghij
1154 TyperInfo(typer_instance),
1155 pretty_exceptions_short=typer_instance.pretty_exceptions_short,
1156 rich_markup_mode=typer_instance.rich_markup_mode,
1157 suggest_commands=typer_instance.suggest_commands,
1158 )
1159 return group 1abcdefghij
1162def get_command(typer_instance: Typer) -> _click.Command: 1abcdefghij
1163 if typer_instance._add_completion: 1abcdefghij
1164 click_install_param, click_show_param = get_install_completion_arguments() 1abcdefghij
1165 if ( 1a
1166 typer_instance.registered_callback
1167 or typer_instance.info.callback
1168 or typer_instance.registered_groups
1169 or len(typer_instance.registered_commands) > 1
1170 ):
1171 # Create a Group
1172 click_command: _click.Command = get_group(typer_instance) 1abcdefghij
1173 if typer_instance._add_completion: 1abcdefghij
1174 click_command.params.append(click_install_param) 1abcdefghij
1175 click_command.params.append(click_show_param) 1abcdefghij
1176 return click_command 1abcdefghij
1177 elif len(typer_instance.registered_commands) == 1: 1abcdefghij
1178 # Create a single Command
1179 single_command = typer_instance.registered_commands[0] 1abcdefghij
1181 if not single_command.context_settings and not isinstance( 1abcdefghij
1182 typer_instance.info.context_settings, DefaultPlaceholder
1183 ):
1184 single_command.context_settings = typer_instance.info.context_settings 1abcdefghij
1186 click_command = get_command_from_info( 1abcdefghij
1187 single_command,
1188 pretty_exceptions_short=typer_instance.pretty_exceptions_short,
1189 rich_markup_mode=typer_instance.rich_markup_mode,
1190 )
1191 if typer_instance._add_completion: 1abcdefghij
1192 click_command.params.append(click_install_param) 1abcdefghij
1193 click_command.params.append(click_show_param) 1abcdefghij
1194 return click_command 1abcdefghij
1195 raise RuntimeError(
1196 "Could not get a command for this Typer instance"
1197 ) # pragma: no cover
1200def solve_typer_info_help(typer_info: TyperInfo) -> str: 1abcdefghij
1201 # Priority 1: Explicit value was set in app.add_typer()
1202 if not isinstance(typer_info.help, DefaultPlaceholder): 1abcdefghij
1203 return inspect.cleandoc(typer_info.help or "") 1abcdefghij
1204 # Priority 2: Explicit value was set in sub_app.callback()
1205 if typer_info.typer_instance and typer_info.typer_instance.registered_callback: 1abcdefghij
1206 callback_help = typer_info.typer_instance.registered_callback.help 1abcdefghij
1207 if not isinstance(callback_help, DefaultPlaceholder): 1abcdefghij
1208 return inspect.cleandoc(callback_help or "") 1abcdefghij
1209 # Priority 3: Explicit value was set in sub_app = typer.Typer()
1210 if typer_info.typer_instance and typer_info.typer_instance.info: 1abcdefghij
1211 instance_help = typer_info.typer_instance.info.help 1abcdefghij
1212 if not isinstance(instance_help, DefaultPlaceholder): 1abcdefghij
1213 return inspect.cleandoc(instance_help or "") 1abcdefghij
1214 # Priority 4: Implicit inference from callback docstring in app.add_typer()
1215 if typer_info.callback: 1abcdefghij
1216 doc = inspect.getdoc(typer_info.callback) 1abcdefghij
1217 if doc: 1abcdefghij
1218 return doc 1abcdefghij
1219 # Priority 5: Implicit inference from callback docstring in @app.callback()
1220 if typer_info.typer_instance and typer_info.typer_instance.registered_callback: 1abcdefghij
1221 callback = typer_info.typer_instance.registered_callback.callback 1abcdefghij
1222 if not isinstance(callback, DefaultPlaceholder): 1abcdefghij
1223 doc = inspect.getdoc(callback or "") 1abcdefghij
1224 if doc: 1abcdefghij
1225 return doc 1abcdefghij
1226 # Priority 6: Implicit inference from callback docstring in typer.Typer()
1227 if typer_info.typer_instance and typer_info.typer_instance.info: 1abcdefghij
1228 instance_callback = typer_info.typer_instance.info.callback 1abcdefghij
1229 if not isinstance(instance_callback, DefaultPlaceholder): 1abcdefghij
1230 doc = inspect.getdoc(instance_callback) 1abcdefghij
1231 if doc: 1abcdefghij
1232 return doc 1abcdefghij
1233 # Value not set, use the default
1234 return typer_info.help.value 1abcdefghij
1237def solve_typer_info_defaults(typer_info: TyperInfo) -> TyperInfo: 1abcdefghij
1238 values: dict[str, Any] = {} 1abcdefghij
1239 for name, value in typer_info.__dict__.items(): 1abcdefghij
1240 # Priority 1: Value was set in app.add_typer()
1241 if not isinstance(value, DefaultPlaceholder): 1abcdefghij
1242 values[name] = value 1abcdefghij
1243 continue 1abcdefghij
1244 # Priority 2: Value was set in @subapp.callback()
1245 try: 1abcdefghij
1246 callback_value = getattr( 1abcdefghij
1247 typer_info.typer_instance.registered_callback, # type: ignore
1248 name,
1249 )
1250 if not isinstance(callback_value, DefaultPlaceholder): 1abcdefghij
1251 values[name] = callback_value 1abcdefghij
1252 continue 1abcdefghij
1253 except AttributeError: 1abcdefghij
1254 pass 1abcdefghij
1255 # Priority 3: Value set in subapp = typer.Typer()
1256 try: 1abcdefghij
1257 instance_value = getattr( 1abcdefghij
1258 typer_info.typer_instance.info, # type: ignore
1259 name,
1260 )
1261 if not isinstance(instance_value, DefaultPlaceholder): 1abcdefghij
1262 values[name] = instance_value 1abcdefghij
1263 continue 1abcdefghij
1264 except AttributeError: 1abcdefghij
1265 pass 1abcdefghij
1266 # Value not set, use the default
1267 values[name] = value.value 1abcdefghij
1268 values["help"] = solve_typer_info_help(typer_info) 1abcdefghij
1269 return TyperInfo(**values) 1abcdefghij
1272def get_group_from_info( 1abcdefghij
1273 group_info: TyperInfo,
1274 *,
1275 pretty_exceptions_short: bool,
1276 suggest_commands: bool,
1277 rich_markup_mode: MarkupMode,
1278) -> TyperGroup:
1279 assert group_info.typer_instance, ( 1abcdefghij
1280 "A Typer instance is needed to generate a Click Group"
1281 )
1282 commands: dict[str, _click.Command] = {} 1abcdefghij
1283 for command_info in group_info.typer_instance.registered_commands: 1abcdefghij
1284 command = get_command_from_info( 1abcdefghij
1285 command_info=command_info,
1286 pretty_exceptions_short=pretty_exceptions_short,
1287 rich_markup_mode=rich_markup_mode,
1288 )
1289 if command.name: 1abcdefghij
1290 commands[command.name] = command 1abcdefghij
1291 for sub_group_info in group_info.typer_instance.registered_groups: 1abcdefghij
1292 sub_group = get_group_from_info( 1abcdefghij
1293 sub_group_info,
1294 pretty_exceptions_short=pretty_exceptions_short,
1295 rich_markup_mode=rich_markup_mode,
1296 suggest_commands=suggest_commands,
1297 )
1298 if sub_group.name: 1abcdefghij
1299 commands[sub_group.name] = sub_group 1abcdefghij
1300 else:
1301 if sub_group.callback: 1abcdefghij
1302 import warnings 1abcdefghij
1304 warnings.warn( 1abcdefghij
1305 "The 'callback' parameter is not supported by Typer when using `add_typer` without a name",
1306 stacklevel=5,
1307 )
1308 for sub_command_name, sub_command in sub_group.commands.items(): 1abcdefghij
1309 commands[sub_command_name] = sub_command 1abcdefghij
1310 solved_info = solve_typer_info_defaults(group_info) 1abcdefghij
1311 params, context_param_name = _get_params_name_from_function(solved_info.callback) 1abcdefghij
1312 cls = solved_info.cls or TyperGroup 1abcdefghij
1313 assert issubclass(cls, TyperGroup), f"{cls} should be a subclass of {TyperGroup}" 1abcdefghij
1314 group = cls( 1abcdefghij
1315 name=solved_info.name or "",
1316 commands=commands,
1317 invoke_without_command=solved_info.invoke_without_command,
1318 no_args_is_help=solved_info.no_args_is_help,
1319 subcommand_metavar=solved_info.subcommand_metavar,
1320 result_callback=solved_info.result_callback,
1321 context_settings=solved_info.context_settings,
1322 callback=get_callback(
1323 callback=solved_info.callback,
1324 params=params,
1325 context_param_name=context_param_name,
1326 pretty_exceptions_short=pretty_exceptions_short,
1327 ),
1328 params=params,
1329 help=solved_info.help,
1330 epilog=solved_info.epilog,
1331 short_help=solved_info.short_help,
1332 options_metavar=solved_info.options_metavar,
1333 add_help_option=solved_info.add_help_option,
1334 hidden=solved_info.hidden,
1335 deprecated=solved_info.deprecated,
1336 rich_markup_mode=rich_markup_mode,
1337 # Rich settings
1338 rich_help_panel=solved_info.rich_help_panel,
1339 suggest_commands=suggest_commands,
1340 )
1341 return group 1abcdefghij
1344def get_command_name(name: str) -> str: 1abcdefghij
1345 return name.lower().replace("_", "-") 1abcdefghij
1348def get_default_option_flag_name(name: str) -> str: 1abcdefghij
1349 return name.replace("_", "-") 1abcdefghij
1352def _get_params_name_from_function( 1abcdefghij
1353 callback: Callable[..., Any] | None,
1354) -> tuple[list[TyperArgument | TyperOption], str | None]:
1355 params = [] 1abcdefghij
1356 context_param_name = None 1abcdefghij
1357 if callback: 1abcdefghij
1358 parameters = get_params_from_function(callback) 1abcdefghij
1359 for param_name, param in parameters.items(): 1abcdefghij
1360 if lenient_issubclass(param.annotation, _click.Context): 1abcdefghij
1361 context_param_name = param_name 1abcdefghij
1362 continue 1abcdefghij
1363 params.append(_get_param(param)) 1abcdefghij
1364 return params, context_param_name 1abcdefghij
1367def get_command_from_info( 1abcdefghij
1368 command_info: CommandInfo,
1369 *,
1370 pretty_exceptions_short: bool,
1371 rich_markup_mode: MarkupMode,
1372) -> _click.Command:
1373 assert command_info.callback, "A command must have a callback function" 1abcdefghij
1374 name = command_info.name or get_command_name(command_info.callback.__name__) # ty: ignore 1abcdefghij
1375 use_help = command_info.help 1abcdefghij
1376 if use_help is None: 1abcdefghij
1377 use_help = inspect.getdoc(command_info.callback) 1abcdefghij
1378 else:
1379 use_help = inspect.cleandoc(use_help) 1abcdefghij
1380 params, context_param_name = _get_params_name_from_function(command_info.callback) 1abcdefghij
1381 cls = command_info.cls or TyperCommand 1abcdefghij
1382 command = cls( 1abcdefghij
1383 name=name,
1384 context_settings=command_info.context_settings,
1385 callback=get_callback(
1386 callback=command_info.callback,
1387 params=params,
1388 context_param_name=context_param_name,
1389 pretty_exceptions_short=pretty_exceptions_short,
1390 ),
1391 params=params, # type: ignore
1392 help=use_help,
1393 epilog=command_info.epilog,
1394 short_help=command_info.short_help,
1395 options_metavar=command_info.options_metavar,
1396 add_help_option=command_info.add_help_option,
1397 no_args_is_help=command_info.no_args_is_help,
1398 hidden=command_info.hidden,
1399 deprecated=command_info.deprecated,
1400 rich_markup_mode=rich_markup_mode,
1401 # Rich settings
1402 rich_help_panel=command_info.rich_help_panel,
1403 )
1404 return command 1abcdefghij
1407def _normalize_collection_value(param: _click.Parameter, value: Any) -> Any: 1abcdefghij
1408 if value is None: 1abcdefghij
1409 return None 1abcdefghij
1410 is_multi = getattr(param, "multiple", False) or getattr(param, "nargs", 1) == -1 1abcdefghij
1411 if not is_multi: 1abcdefghij
1412 return value 1abcdefghij
1413 if param.default is None and len(value) == 0: 1abcdefghij
1414 return None 1abcdefghij
1415 return list(value) 1abcdefghij
1418def get_callback( 1abcdefghij
1419 *,
1420 callback: Callable[..., Any] | None = None,
1421 params: Sequence[_click.Parameter] = [],
1422 context_param_name: str | None = None,
1423 pretty_exceptions_short: bool,
1424) -> Callable[..., Any] | None:
1425 if not callback: 1abcdefghij
1426 return None 1abcdefghij
1427 parameters = get_params_from_function(callback) 1abcdefghij
1428 use_params: dict[str, Any] = {} 1abcdefghij
1429 for param_name in parameters: 1abcdefghij
1430 use_params[param_name] = None 1abcdefghij
1431 params_by_name: dict[str, _click.Parameter] = {} 1abcdefghij
1432 for param in params: 1abcdefghij
1433 if param.name: 1abcdefghij
1434 use_params[param.name] = param.default 1abcdefghij
1435 params_by_name[param.name] = param 1abcdefghij
1437 def wrapper(**kwargs: Any) -> Any: 1abcdefghij
1438 _rich_traceback_guard = pretty_exceptions_short # noqa: F841 1abcdefghij
1439 for k, v in kwargs.items(): 1abcdefghij
1440 matched_param = params_by_name.get(k) 1abcdefghij
1441 assert matched_param is not None 1abcdefghij
1442 use_params[k] = _normalize_collection_value(matched_param, v) 1abcdefghij
1443 if context_param_name: 1abcdefghij
1444 use_params[context_param_name] = get_current_context() 1abcdefghij
1445 return callback(**use_params) 1abcdefghij
1447 update_wrapper(wrapper, callback) 1abcdefghij
1448 return wrapper 1abcdefghij
1451def _get_param(param: ParamMeta) -> TyperArgument | TyperOption: 1abcdefghij
1452 default_value = None 1abcdefghij
1453 required = False 1abcdefghij
1454 if isinstance(param.default, ParameterInfo): 1abcdefghij
1455 parameter_info = param.default 1abcdefghij
1456 if parameter_info.default == Required: 1abcdefghij
1457 required = True 1abcdefghij
1458 else:
1459 default_value = parameter_info.default 1abcdefghij
1460 elif param.default == Required or param.default is param.empty: 1abcdefghij
1461 required = True 1abcdefghij
1462 parameter_info = ArgumentInfo() 1abcdefghij
1463 else:
1464 default_value = param.default 1abcdefghij
1465 parameter_info = OptionInfo() 1abcdefghij
1467 annotation = parse_param_annotation(param, default_value) 1abcdefghij
1468 annotation_args = get_args(annotation) 1abcdefghij
1469 is_list = lenient_issubclass(get_origin(annotation), list) 1abcdefghij
1470 is_flag = None 1abcdefghij
1471 if isinstance(parameter_info, OptionInfo): 1abcdefghij
1472 if annotation is bool: 1abcdefghij
1473 is_flag = True 1abcdefghij
1474 elif ( 1a
1475 is_list
1476 and annotation_args == (bool,)
1477 and parameter_info.param_decls
1478 and any("/" in decl for decl in parameter_info.param_decls)
1479 ):
1480 is_flag = True 1abcdefghij
1481 descriptor = resolve_type_descriptor( 1abcdefghij
1482 annotation=annotation,
1483 parameter_info=parameter_info,
1484 )
1485 tuple_nargs = descriptor.tuple_arity 1abcdefghij
1487 if isinstance(parameter_info, OptionInfo): 1abcdefghij
1488 default_option_name = get_default_option_flag_name(param.name) 1abcdefghij
1489 if is_flag: 1abcdefghij
1490 default_option_declaration = ( 1abcdefghij
1491 f"--{default_option_name}/--no-{default_option_name}"
1492 )
1493 else:
1494 default_option_declaration = f"--{default_option_name}" 1abcdefghij
1495 param_decls = [param.name] 1abcdefghij
1496 if parameter_info.param_decls: 1abcdefghij
1497 param_decls.extend(parameter_info.param_decls) 1abcdefghij
1498 else:
1499 param_decls.append(default_option_declaration) 1abcdefghij
1500 return TyperOption( 1abcdefghij
1501 # Option
1502 param_decls=param_decls,
1503 show_default=parameter_info.show_default,
1504 prompt=parameter_info.prompt,
1505 confirmation_prompt=parameter_info.confirmation_prompt,
1506 prompt_required=parameter_info.prompt_required,
1507 hide_input=parameter_info.hide_input,
1508 is_flag=is_flag,
1509 multiple=is_list,
1510 count=parameter_info.count,
1511 allow_from_autoenv=parameter_info.allow_from_autoenv,
1512 help=parameter_info.help,
1513 hidden=parameter_info.hidden,
1514 show_choices=parameter_info.show_choices,
1515 show_envvar=parameter_info.show_envvar,
1516 # Parameter
1517 required=required,
1518 default=default_value,
1519 callback=get_param_callback(callback=parameter_info.callback),
1520 metavar=parameter_info.metavar,
1521 expose_value=parameter_info.expose_value,
1522 is_eager=parameter_info.is_eager,
1523 envvar=parameter_info.envvar,
1524 shell_complete=parameter_info.shell_complete,
1525 autocompletion=get_param_completion(parameter_info.autocompletion),
1526 min=parameter_info.min,
1527 max=parameter_info.max,
1528 nargs=tuple_nargs,
1529 # Rich settings
1530 rich_help_panel=parameter_info.rich_help_panel,
1531 type_descriptor=descriptor,
1532 )
1533 elif isinstance(parameter_info, ArgumentInfo): 1abcdefghij
1534 param_decls = [param.name] 1abcdefghij
1535 nargs = None 1abcdefghij
1536 if is_list: 1abcdefghij
1537 nargs = -1 1abcdefghij
1538 elif tuple_nargs is not None: 1abcdefghij
1539 nargs = tuple_nargs 1abcdefghij
1540 return TyperArgument( 1abcdefghij
1541 # Argument
1542 param_decls=param_decls,
1543 required=required,
1544 nargs=nargs,
1545 # TyperArgument
1546 show_default=parameter_info.show_default,
1547 show_choices=parameter_info.show_choices,
1548 show_envvar=parameter_info.show_envvar,
1549 help=parameter_info.help,
1550 hidden=parameter_info.hidden,
1551 # Parameter
1552 default=default_value,
1553 callback=get_param_callback(callback=parameter_info.callback),
1554 metavar=parameter_info.metavar,
1555 expose_value=parameter_info.expose_value,
1556 is_eager=parameter_info.is_eager,
1557 envvar=parameter_info.envvar,
1558 shell_complete=parameter_info.shell_complete,
1559 autocompletion=get_param_completion(parameter_info.autocompletion),
1560 min=parameter_info.min,
1561 max=parameter_info.max,
1562 # Rich settings
1563 rich_help_panel=parameter_info.rich_help_panel,
1564 type_descriptor=descriptor,
1565 )
1566 raise AssertionError("A Parameter should be returned") # pragma: no cover
1569def get_param_callback( 1abcdefghij
1570 *,
1571 callback: Callable[..., Any] | None = None,
1572) -> Callable[..., Any] | None:
1573 if not callback: 1abcdefghij
1574 return None 1abcdefghij
1575 parameters = get_params_from_function(callback) 1abcdefghij
1576 ctx_name = None 1abcdefghij
1577 param_arg_name = None 1abcdefghij
1578 value_name = None 1abcdefghij
1579 untyped_names: list[str] = [] 1abcdefghij
1580 for param_name, param_sig in parameters.items(): 1abcdefghij
1581 if lenient_issubclass(param_sig.annotation, _click.Context): 1abcdefghij
1582 ctx_name = param_name 1abcdefghij
1583 elif lenient_issubclass(param_sig.annotation, _click.Parameter): 1abcdefghij
1584 param_arg_name = param_name 1abcdefghij
1585 else:
1586 untyped_names.append(param_name) 1abcdefghij
1587 # Extract value param name first
1588 if untyped_names: 1abcdefghij
1589 value_name = untyped_names.pop() 1abcdefghij
1590 # If context and parameter were not typed, extract them by position.
1591 if untyped_names: 1abcdefghij
1592 if ctx_name is None: 1abcdefghij
1593 ctx_name = untyped_names.pop(0) 1abcdefghij
1594 if param_arg_name is None: 1abcdefghij
1595 if untyped_names: 1abcdefghij
1596 param_arg_name = untyped_names.pop(0) 1abcdefghij
1597 if untyped_names: 1abcdefghij
1598 raise _click.ClickException( 1abcdefghij
1599 "Too many CLI parameter callback function parameters"
1600 )
1602 def wrapper(ctx: _click.Context, param: _click.Parameter, value: Any) -> Any: 1abcdefghij
1603 use_params: dict[str, Any] = {} 1abcdefghij
1604 if ctx_name: 1abcdefghij
1605 use_params[ctx_name] = ctx 1abcdefghij
1606 if param_arg_name: 1abcdefghij
1607 use_params[param_arg_name] = param 1abcdefghij
1608 if value_name: 1abcdefghij
1609 use_params[value_name] = _normalize_collection_value(param, value) 1abcdefghij
1610 return callback(**use_params) 1abcdefghij
1612 update_wrapper(wrapper, callback) 1abcdefghij
1613 return wrapper 1abcdefghij
1616def get_param_completion( 1abcdefghij
1617 callback: Callable[..., Any] | None = None,
1618) -> Callable[..., Any] | None:
1619 if not callback: 1abcdefghij
1620 return None 1abcdefghij
1621 parameters = get_params_from_function(callback) 1abcdefghij
1622 ctx_name = None 1abcdefghij
1623 args_name = None 1abcdefghij
1624 incomplete_name = None 1abcdefghij
1625 unassigned_params = list(parameters.values()) 1abcdefghij
1626 for param_sig in unassigned_params[:]: 1abcdefghij
1627 origin = get_origin(param_sig.annotation) 1abcdefghij
1628 if lenient_issubclass(param_sig.annotation, _click.Context): 1abcdefghij
1629 ctx_name = param_sig.name 1abcdefghij
1630 unassigned_params.remove(param_sig) 1abcdefghij
1631 elif lenient_issubclass(origin, list): 1abcdefghij
1632 args_name = param_sig.name 1abcdefghij
1633 unassigned_params.remove(param_sig) 1abcdefghij
1634 elif lenient_issubclass(param_sig.annotation, str): 1abcdefghij
1635 incomplete_name = param_sig.name 1abcdefghij
1636 unassigned_params.remove(param_sig) 1abcdefghij
1637 # If there are still unassigned parameters (not typed), extract by name
1638 for param_sig in unassigned_params[:]: 1abcdefghij
1639 if ctx_name is None and param_sig.name == "ctx": 1abcdefghij
1640 ctx_name = param_sig.name 1abcdefghij
1641 unassigned_params.remove(param_sig) 1abcdefghij
1642 elif args_name is None and param_sig.name == "args": 1abcdefghij
1643 args_name = param_sig.name 1abcdefghij
1644 unassigned_params.remove(param_sig) 1abcdefghij
1645 elif incomplete_name is None and param_sig.name == "incomplete": 1abcdefghij
1646 incomplete_name = param_sig.name 1abcdefghij
1647 unassigned_params.remove(param_sig) 1abcdefghij
1648 # Extract value param name first
1649 if unassigned_params: 1abcdefghij
1650 show_params = " ".join([param.name for param in unassigned_params]) 1abcdefghij
1651 raise _click.ClickException( 1abcdefghij
1652 f"Invalid autocompletion callback parameters: {show_params}"
1653 )
1655 def wrapper(ctx: _click.Context, args: list[str], incomplete: str | None) -> Any: 1abcdefghij
1656 use_params: dict[str, Any] = {} 1abcdefghij
1657 if ctx_name: 1abcdefghij
1658 use_params[ctx_name] = ctx 1abcdefghij
1659 if args_name: 1abcdefghij
1660 use_params[args_name] = args 1abcdefghij
1661 if incomplete_name: 1abcdefghij
1662 use_params[incomplete_name] = incomplete 1abcdefghij
1663 return callback(**use_params) 1abcdefghij
1665 update_wrapper(wrapper, callback) 1abcdefghij
1666 return wrapper 1abcdefghij
1669def run( 1abcdefghij
1670 function: Annotated[
1671 Callable[..., Any],
1672 Doc(
1673 """
1674 The function that should power this CLI application.
1675 """
1676 ),
1677 ],
1678) -> None:
1679 """
1680 This function converts a given function to a CLI application with `Typer()` and executes it.
1682 ## Example
1684 ```python
1685 import typer
1687 def main(name: str):
1688 print(f"Hello {name}")
1690 if __name__ == "__main__":
1691 typer.run(main)
1692 ```
1693 """
1694 app = Typer(add_completion=False) 1abcdefghij
1695 app.command()(function) 1abcdefghij
1696 app() 1abcdefghij
1699def _is_macos() -> bool: 1abcdefghij
1700 return platform.system() == "Darwin" 1abcdefghij
1703def _is_linux_or_bsd() -> bool: 1abcdefghij
1704 if platform.system() == "Linux": 1abcdefghij
1705 return True 1abcdefghij
1707 return "BSD" in platform.system() 1abcdefghij
1710def launch( 1abcdefghij
1711 url: Annotated[
1712 str,
1713 Doc(
1714 """
1715 URL or filename of the thing to launch.
1716 """
1717 ),
1718 ],
1719 wait: Annotated[
1720 bool,
1721 Doc(
1722 """
1723 Wait for the program to exit before returning. This only works if the launched program blocks.
1724 """
1725 ),
1726 ] = False,
1727 locate: Annotated[
1728 bool,
1729 Doc(
1730 """
1731 If this is set to `True`, then instead of launching the application associated with the URL, it will attempt to
1732 launch a file manager with the file located. This might have weird effects if the URL does not point to the filesystem.
1733 """
1734 ),
1735 ] = False,
1736) -> int:
1737 """
1738 This function launches the given URL (or filename) in the default
1739 viewer application for this file type. If this is an executable, it
1740 might launch the executable in a new session. The return value is
1741 the exit code of the launched application. Usually, `0` indicates
1742 success.
1744 This function handles url in different operating systems separately:
1745 - On macOS (Darwin), it uses the `open` command.
1746 - On Linux and BSD, it uses `xdg-open` if available.
1747 - On Windows (and other OSes), it uses the standard webbrowser module.
1749 The function avoids, when possible, using the webbrowser module on Linux and macOS
1750 to prevent spammy terminal messages from some browsers (e.g., Chrome).
1752 ## Examples
1753 ```python
1754 import typer
1756 typer.launch("https://typer.tiangolo.com/")
1757 ```
1759 ```python
1760 import typer
1762 typer.launch("/my/downloaded/file", locate=True)
1763 ```
1764 """
1766 if url.startswith("http://") or url.startswith("https://"): 1abcdefghij
1767 if _is_macos(): 1abcdefghij
1768 return subprocess.Popen( 1abcdefghij
1769 ["open", url], stdout=subprocess.DEVNULL, stderr=subprocess.STDOUT
1770 ).wait()
1772 has_xdg_open = _is_linux_or_bsd() and shutil.which("xdg-open") is not None 1abcdefghij
1774 if has_xdg_open: 1abcdefghij
1775 process = subprocess.Popen( 1abcdefghij
1776 ["xdg-open", url], stdout=subprocess.DEVNULL, stderr=subprocess.STDOUT
1777 )
1778 if wait: 1abcdefghij
1779 return process.wait() 1abcdefghij
1780 return 0 1abcdefghij
1782 import webbrowser 1abcdefghij
1784 webbrowser.open(url) 1abcdefghij
1786 return 0 1abcdefghij
1788 else:
1789 return _click.launch(url, wait=wait, locate=locate) 1abcdefghij