✨ Richify, add integrations with Rich everywhere (#419)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Sebastián Ramírez · committed by GitHub · parent 8212e73 · Browse files · 250 files·+3488 added−705 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
250 files+3488 added−705 removed
- tests:+830 added−158 removed
- other:+2658 added−547 removed
Provenance
- Commit
6208b5b- Tree
beacb14- Author
Sebastián Ramírez <tiangolo@gmail.com>- Committer
GitHub <noreply@github.com>- Parent
8212e73
250 files changed+3488 added−705 removed
modified:docs/css/termynal.css+3 added-1 removed
15 unmodified lines1617181920202122232425262728293031323377 unmodified lines15 unmodified lines width: 750px; max-width: 100%; background: var(--color-bg); color: var(--color-text); /* font-size: 18px; */ font-size: 18px; font-size: 15px; /* font-family: 'Fira Mono', Consolas, Menlo, Monaco, 'Courier New', Courier, monospace; */ font-family: 'Roboto Mono', 'Fira Mono', Consolas, Menlo, Monaco, 'Courier New', Courier, monospace; border-radius: 4px; padding: 75px 45px 35px; position: relative; -webkit-box-sizing: border-box; box-sizing: border-box; line-height: 1.2;}
[data-termynal]:before { content: '';77 unmodified linesmodified:docs/tutorial/arguments/help.md+51 added-1 removed
209 unmodified lines210 ```211 212 </div>213 214+## *CLI Argument* help panels215+216+You might want to show the help information for *CLI arguments* in different panels when using the `--help` option.217+218+If you have installed Rich as described in the docs for [Printing and Colors](../printing.md){.internal-link target=_blank}, you can set the `rich_help_panel` parameter to the name of the panel where you want this *CLI argument* to be shown:219+220+```Python hl_lines="7 10"221+{!../docs_src/arguments/help/tutorial007.py!}222+```223+224+Then, if you check the `--help` option, you will see a default panel named "`Arguments`" for the *CLI arguments* that don't have a custom `rich_help_panel`.225+226+And next you will see other panels for the *CLI arguments* that have a custom panel set in the `rich_help_panel` parameter:227+228+<div class="termy">229+230+```console231+$ python main.py --help232+233+<b> </b><font color="#F4BF75"><b>Usage: </b></font><b>main.py [OPTIONS] NAME [LASTNAME] [AGE] </b>234+<b> </b>235+ Say hi to NAME very gently, like Dirk.236+237+<font color="#A5A5A1">╭─ Arguments ───────────────────────────────────────────────────────╮</font>238+<font color="#A5A5A1">│ </font><font color="#F92672">*</font> name <font color="#F4BF75"><b>TEXT</b></font> Who to greet [default: None] <font color="#A6194C">[required]</font> │239+<font color="#A5A5A1">╰───────────────────────────────────────────────────────────────────╯</font>240+<font color="#A5A5A1">╭─ Secondary Arguments ─────────────────────────────────────────────╮</font>241+<font color="#A5A5A1">│ lastname </font><font color="#A37F4E"><b>[LASTNAME]</b></font> The last name │242+<font color="#A5A5A1">│ age </font><font color="#A37F4E"><b>[AGE] </b></font> The user's age │243+<font color="#A5A5A1">╰───────────────────────────────────────────────────────────────────╯</font>244+<font color="#A5A5A1">╭─ Options ─────────────────────────────────────────────────────────╮</font>245+<font color="#A5A5A1">│ </font><font color="#A1EFE4"><b>--install-completion</b></font> Install completion for the current │246+<font color="#A5A5A1">│ shell. │</font>247+<font color="#A5A5A1">│ </font><font color="#A1EFE4"><b>--show-completion</b></font> Show completion for the current │248+<font color="#A5A5A1">│ shell, to copy it or customize the │</font>249+<font color="#A5A5A1">│ installation. │</font>250+<font color="#A5A5A1">│ </font><font color="#A1EFE4"><b>--help</b></font> Show this message and exit. │251+<font color="#A5A5A1">╰───────────────────────────────────────────────────────────────────╯</font>252+```253+254+</div>255+256+In this example we have a custom *CLI arguments* panel named "`Secondary Arguments`".257+258+## Help with style using Rich259+260+In a future section you will see how to use custom markup in the `help` for *CLI arguments* when reading about [Commands - Command Help](../commands/help.md#rich-markdown-and-markup){.internal-link target=_blank}.261+262+If you are in a hurry you can jump there, but otherwise, it would be better to continue reading here and following the tutorial in order.263+264 ## Hide a *CLI argument* from the help text265 266 If you want, you can make a *CLI argument* **not** show up in the `Arguments` section in the help text.267 268 You will probably not want to do this normally, but it's possible:269 270 ```Python hl_lines="4"221-{!../docs_src/arguments/help/tutorial007.py!}271+{!../docs_src/arguments/help/tutorial008.py!}272 ```273 274 Check it:275 45 unmodified linesmodified:docs/tutorial/commands/help.md+366 added
116 unmodified lines117 // It uses "Create a new user with USERNAME." instead of "Some internal utility function to create."118 ```119 120 </div>121+122+## Deprecate a Command123+124+There could be cases where you have a command in your app that you need to deprecate, so that your users stop using it, even while it's still supported for a while.125+126+You can mark it with the parameter `deprecated=True`:127+128+```Python hl_lines="14"129+{!../docs_src/commands/help/tutorial003.py!}130+```131+132+And when you show the `--help` option you will see it's marked as "`deprecated`":133+134+<div class="termy">135+136+```console137+$ python main.py --help138+139+<b> </b><font color="#F4BF75"><b>Usage: </b></font><b>main.py [OPTIONS] COMMAND [ARGS]... </b>140+<b> </b>141+<font color="#A5A5A1">╭─ Options ─────────────────────────────────────────────────────────╮</font>142+<font color="#A5A5A1">│ </font><font color="#A1EFE4"><b>--install-completion</b></font> Install completion for the current │143+<font color="#A5A5A1">│ shell. │</font>144+<font color="#A5A5A1">│ </font><font color="#A1EFE4"><b>--show-completion</b></font> Show completion for the current │145+<font color="#A5A5A1">│ shell, to copy it or customize the │</font>146+<font color="#A5A5A1">│ installation. │</font>147+<font color="#A5A5A1">│ </font><font color="#A1EFE4"><b>--help</b></font> Show this message and exit. │148+<font color="#A5A5A1">╰───────────────────────────────────────────────────────────────────╯</font>149+<font color="#A5A5A1">╭─ Commands ────────────────────────────────────────────────────────╮</font>150+<font color="#A5A5A1">│ </font><font color="#A1EFE4"><b>create </b></font> Create a user. │151+<font color="#A5A5A1">│ </font><font color="#6B9F98"><b>delete </b></font> Delete a user. <font color="#F92672">(deprecated) </font> │152+<font color="#A5A5A1">╰───────────────────────────────────────────────────────────────────╯</font>153+```154+155+</div>156+157+And if you check the `--help` for the deprecated command (in this example, the command `delete`), it also shows it as deprecated:158+159+<div class="termy">160+161+```console162+$ python main.py delete --help163+164+<b> </b><font color="#F4BF75"><b>Usage: </b></font><b>main.py delete [OPTIONS] USERNAME </b>165+<b> </b>166+ <font color="#F92672">(deprecated) </font>167+ Delete a user.168+ This is deprecated and will stop being supported soon.169+170+<font color="#A5A5A1">╭─ Arguments ───────────────────────────────────────────────────────╮</font>171+<font color="#A5A5A1">│ </font><font color="#F92672">*</font> username <font color="#F4BF75"><b>TEXT</b></font> [default: None] <font color="#A6194C">[required]</font> │172+<font color="#A5A5A1">╰───────────────────────────────────────────────────────────────────╯</font>173+<font color="#A5A5A1">╭─ Options ─────────────────────────────────────────────────────────╮</font>174+<font color="#A5A5A1">│ </font><font color="#A1EFE4"><b>--help</b></font> Show this message and exit. │175+<font color="#A5A5A1">╰───────────────────────────────────────────────────────────────────╯</font>176+```177+178+</div>179+180+## Rich Markdown and Markup181+182+If you have **Rich** installed as described in [Printing and Colors](../printing.md){.internal-link target=_blank}, you can configure your app to enable markup text with the parameter `rich_markup_mode`.183+184+Then you can use more formatting in the docstrings and the `help` parameter for *CLI arguments* and *CLI options*. You will see more about it below. 👇185+186+!!! info187+ By default, `rich_markup_mode` is `None`, which disables any rich text formatting.188+189+### Rich Markup190+191+If you set `rich_markup_mode="rich"` when creating the `typer.Typer()` app, you will be able to use <a href="https://rich.readthedocs.io/en/stable/markup.html" class="external-link" target="_blank">Rich Console Markup</a> in the docstring, and even in the help for the *CLI arguments* and options:192+193+```Python hl_lines="3 9 13-15 20 22 24"194+{!../docs_src/commands/help/tutorial004.py!}195+```196+197+With that, you can use <a href="https://rich.readthedocs.io/en/stable/markup.html" class="external-link" target="_blank">Rich Console Markup</a> to format the text in the docstring for the command `create`, make the word "`create`" bold and green, and even use an <a href="https://rich.readthedocs.io/en/stable/markup.html#emoji" class="external-link" target="_blank">emoji</a>.198+199+You can also use markup in the help for the `username` CLI Argument.200+201+And the same as before, the help text overwritten for the command `delete` can also use Rich Markup, the same in the CLI Argument and CLI Option.202+203+If you run the program and check the help, you will see that **Typer** uses **Rich** internally to format the help.204+205+Check the help for the `create` command:206+207+<div class="termy">208+209+```console210+$ python main.py create --help211+212+<b> </b><font color="#F4BF75"><b>Usage: </b></font><b>main.py create [OPTIONS] USERNAME </b>213+<b> </b>214+ <font color="#A6E22E"><b>Create</b></font> a new <i>shinny</i> user. ✨215+ This requires a <font color="#A5A5A1"><u style="text-decoration-style:single">username</u></font><font color="#A5A5A1">. </font>216+217+<font color="#A5A5A1">╭─ Arguments ───────────────────────────────────────────────────────╮</font>218+<font color="#A5A5A1">│ </font><font color="#F92672">*</font> username <font color="#F4BF75"><b>TEXT</b></font> The username to be <font color="#A6E22E">created</font> │219+<font color="#A5A5A1">│ [default: None] │</font>220+<font color="#A5A5A1">│ </font><font color="#A6194C">[required] </font> │221+<font color="#A5A5A1">╰───────────────────────────────────────────────────────────────────╯</font>222+<font color="#A5A5A1">╭─ Options ─────────────────────────────────────────────────────────╮</font>223+<font color="#A5A5A1">│ </font><font color="#A1EFE4"><b>--help</b></font> Show this message and exit. │224+<font color="#A5A5A1">╰───────────────────────────────────────────────────────────────────╯</font>225+```226+227+</div>228+229+And check the help for the `delete` command:230+231+<div class="termy">232+233+```console234+$ python main.py delete --help235+236+<b> </b><font color="#F4BF75"><b>Usage: </b></font><b>main.py delete [OPTIONS] USERNAME </b>237+<b> </b>238+ <font color="#F92672"><b>Delete</b></font> a user with <i>USERNAME</i>.239+240+<font color="#A5A5A1">╭─ Arguments ───────────────────────────────────────────────────────╮</font>241+<font color="#A5A5A1">│ </font><font color="#F92672">*</font> username <font color="#F4BF75"><b>TEXT</b></font> The username to be <font color="#F92672">deleted</font> │242+<font color="#A5A5A1">│ [default: None] │</font>243+<font color="#A5A5A1">│ </font><font color="#A6194C">[required] </font> │244+<font color="#A5A5A1">╰───────────────────────────────────────────────────────────────────╯</font>245+<font color="#A5A5A1">╭─ Options ─────────────────────────────────────────────────────────╮</font>246+<font color="#A5A5A1">│ </font><font color="#A1EFE4"><b>--force</b></font> <font color="#AE81FF"><b>--no-force</b></font> Force the <font color="#F92672"><b>deletion</b></font> 💥 │247+<font color="#A5A5A1">│ [default: no-force] │</font>248+<font color="#A5A5A1">│ </font><font color="#A1EFE4"><b>--help</b></font> Show this message and exit. │249+<font color="#A5A5A1">╰───────────────────────────────────────────────────────────────────╯</font>250+```251+252+</div>253+254+### Rich Markown255+256+If you set `rich_markup_mode="markdown"` when creating the `typer.Typer()` app, you will be able to use Markdown in the docstring:257+258+```Python hl_lines="3 7 9-17 22 24-25"259+{!../docs_src/commands/help/tutorial005.py!}260+```261+262+With that, you can use Markdown to format the text in the docstring for the command `create`, make the word "`create`" bold, show a list of items, and even use an <a href="https://rich.readthedocs.io/en/stable/markup.html#emoji" class="external-link" target="_blank">emoji</a>.263+264+And the same as before, the help text overwritten for the command `delete` can also use Markdown.265+266+Check the help for the `create` command:267+268+<div class="termy">269+270+```console271+$ python main.py create --help272+273+<b> </b><font color="#F4BF75"><b>Usage: </b></font><b>main.py create [OPTIONS] USERNAME </b>274+<b> </b>275+ <b>Create</b> a new <i>shinny</i> user. ✨276+277+ <font color="#F4BF75"><b> • </b></font><font color="#A5A5A1">Create a username </font>278+ <font color="#F4BF75"><b> • </b></font><font color="#A5A5A1">Show that the username is created </font>279+280+ <font color="#F4BF75">───────────────────────────────────────────────────────────────────</font>281+ Learn more at the <font color="#44919F">Typer docs website</font>282+283+<font color="#A5A5A1">╭─ Arguments ───────────────────────────────────────────────────────╮</font>284+<font color="#A5A5A1">│ </font><font color="#F92672">*</font> username <font color="#F4BF75"><b>TEXT</b></font> The username to be <b>created</b> │285+<font color="#A5A5A1">│ [default: None] │</font>286+<font color="#A5A5A1">│ </font><font color="#A6194C">[required] </font> │287+<font color="#A5A5A1">╰───────────────────────────────────────────────────────────────────╯</font>288+<font color="#A5A5A1">╭─ Options ─────────────────────────────────────────────────────────╮</font>289+<font color="#A5A5A1">│ </font><font color="#A1EFE4"><b>--help</b></font> Show this message and exit. │290+<font color="#A5A5A1">╰───────────────────────────────────────────────────────────────────╯</font>291+```292+293+</div>294+295+And the same for the `delete` command:296+297+<div class="termy">298+299+```console300+$ python main.py delete --help301+302+<b> </b><font color="#F4BF75"><b>Usage: </b></font><b>main.py delete [OPTIONS] USERNAME </b>303+<b> </b>304+ <b>Delete</b> a user with <i>USERNAME</i>.305+306+<font color="#A5A5A1">╭─ Arguments ───────────────────────────────────────────────────────╮</font>307+<font color="#A5A5A1">│ </font><font color="#F92672">*</font> username <font color="#F4BF75"><b>TEXT</b></font> The username to be <b>deleted</b> │308+<font color="#A5A5A1">│ [default: None] │</font>309+<font color="#A5A5A1">│ </font><font color="#A6194C">[required] </font> │310+<font color="#A5A5A1">╰───────────────────────────────────────────────────────────────────╯</font>311+<font color="#A5A5A1">╭─ Options ─────────────────────────────────────────────────────────╮</font>312+<font color="#A5A5A1">│ </font><font color="#A1EFE4"><b>--force</b></font> <font color="#AE81FF"><b>--no-force</b></font> Force the <b>deletion</b> 💥 │313+<font color="#A5A5A1">│ [default: no-force] │</font>314+<font color="#A5A5A1">│ </font><font color="#A1EFE4"><b>--help</b></font> Show this message and exit. │315+<font color="#A5A5A1">╰───────────────────────────────────────────────────────────────────╯</font>316+```317+318+</div>319+320+!!! info321+ Notice that in Markdown you cannot define colors. For colors you might prefer to use Rich markup.322+323+## Help Panels324+325+If you have many commands or CLI parameters, you might want to show their documentation in different panels when using the `--help` option.326+327+If you installed <a href="https://rich.readthedocs.io/" class="external-link" target="_blank">Rich</a> as described in [Printing and Colors](../printing.md){.internal-link target=_blank}, you can configure the panel to use for each command or CLI parameter.328+329+### Help Panels for Commands330+331+To set the panel for a command you can pass the argument `rich_help_panel` with the name of the panel you want to use:332+333+```Python hl_lines="22 30 38 46"334+{!../docs_src/commands/help/tutorial006.py!}335+```336+337+Commands without a panel will be shown in the default panel `Commands`, and the rest will be shown in the next panels:338+339+<div class="termy">340+341+```console342+$ python main.py --help343+344+<b> </b><font color="#F4BF75"><b>Usage: </b></font><b>main.py [OPTIONS] COMMAND [ARGS]... </b>345+<b> </b>346+<font color="#A5A5A1">╭─ Options ─────────────────────────────────────────────────────────╮</font>347+<font color="#A5A5A1">│ </font><font color="#A1EFE4"><b>--install-completion</b></font> Install completion for the current │348+<font color="#A5A5A1">│ shell. │</font>349+<font color="#A5A5A1">│ </font><font color="#A1EFE4"><b>--show-completion</b></font> Show completion for the current │350+<font color="#A5A5A1">│ shell, to copy it or customize the │</font>351+<font color="#A5A5A1">│ installation. │</font>352+<font color="#A5A5A1">│ </font><font color="#A1EFE4"><b>--help</b></font> Show this message and exit. │353+<font color="#A5A5A1">╰───────────────────────────────────────────────────────────────────╯</font>354+<font color="#A5A5A1">╭─ Commands ────────────────────────────────────────────────────────╮</font>355+<font color="#A5A5A1">│ </font><font color="#A1EFE4"><b>create </b></font> <font color="#A6E22E">Create</font> a new user. ✨ │356+<font color="#A5A5A1">│ </font><font color="#A1EFE4"><b>delete </b></font> <font color="#F92672">Delete</font> a user. 🔥 │357+<font color="#A5A5A1">╰───────────────────────────────────────────────────────────────────╯</font>358+<font color="#A5A5A1">╭─ Utils and Configs ───────────────────────────────────────────────╮</font>359+<font color="#A5A5A1">│ </font><font color="#A1EFE4"><b>config </b></font> <font color="#66D9EF">Configure</font> the system. 🔧 │360+<font color="#A5A5A1">│ </font><font color="#A1EFE4"><b>sync </b></font> <font color="#66D9EF">Synchronize</font> the system or something fancy like that. ♻ │361+<font color="#A5A5A1">╰───────────────────────────────────────────────────────────────────╯</font>362+<font color="#A5A5A1">╭─ Help and Others ─────────────────────────────────────────────────╮</font>363+<font color="#A5A5A1">│ </font><font color="#A1EFE4"><b>help </b></font> Get <font color="#F4BF75">help</font> with the system. ❓ │364+<font color="#A5A5A1">│ </font><font color="#A1EFE4"><b>report </b></font> <font color="#F4BF75">Report</font> an issue. 🐛 │365+<font color="#A5A5A1">╰───────────────────────────────────────────────────────────────────╯</font>366+```367+368+</div>369+370+### Help Panels for CLI Parameters371+372+The same way, you can configure the panels for *CLI arguments* and *CLI options* with `rich_help_panel`.373+374+And of course, in the same application you can also set the `rich_help_panel` for commands.375+376+```Python hl_lines="12 16 21 30"377+{!../docs_src/commands/help/tutorial007.py!}378+```379+380+Then if you run the application you will see all the *CLI parameters* in their respective panels.381+382+* First the ***CLI arguments*** that don't have a panel name set in a **default** one named "`Arguments`".383+* Next the ***CLI arguments*** with a **custom panel**. In this example named "`Secondary Arguments`".384+* After that, the ***CLI options*** that don't have a panel in a **default** one named "`Options`".385+* And finally, the ***CLI options*** with a **custom panel** set. In this example named "`Additional Data`".386+387+You can check the `--help` option for the command `create`:388+389+<div class="termy">390+391+```console392+$ python main.py create --help393+394+<b> </b><font color="#F4BF75"><b>Usage: </b></font><b>main.py create [OPTIONS] USERNAME [LASTNAME] </b>395+<b> </b>396+ <font color="#A6E22E">Create</font> a new user. ✨397+398+<font color="#A5A5A1">╭─ Arguments ───────────────────────────────────────────────────────╮</font>399+<font color="#A5A5A1">│ </font><font color="#F92672">*</font> username <font color="#F4BF75"><b>TEXT</b></font> The username to create [default: None] │400+<font color="#A5A5A1">│ </font><font color="#A6194C">[required] </font> │401+<font color="#A5A5A1">╰───────────────────────────────────────────────────────────────────╯</font>402+<font color="#A5A5A1">╭─ Secondary Arguments ─────────────────────────────────────────────╮</font>403+<font color="#A5A5A1">│ lastname </font><font color="#A37F4E"><b>[LASTNAME]</b></font> The last name of the new user │404+<font color="#A5A5A1">╰───────────────────────────────────────────────────────────────────╯</font>405+<font color="#A5A5A1">╭─ Options ─────────────────────────────────────────────────────────╮</font>406+<font color="#A5A5A1">│ </font><font color="#A1EFE4"><b>--force</b></font> <font color="#AE81FF"><b>--no-force</b></font> Force the creation of the user │407+<font color="#A5A5A1">│ [default: no-force] │</font>408+<font color="#A5A5A1">│ </font><font color="#A1EFE4"><b>--help</b></font> Show this message and exit. │409+<font color="#A5A5A1">╰───────────────────────────────────────────────────────────────────╯</font>410+<font color="#A5A5A1">╭─ Additional Data ─────────────────────────────────────────────────╮</font>411+<font color="#A5A5A1">│ </font><font color="#A1EFE4"><b>--age</b></font> <font color="#F4BF75"><b>INTEGER</b></font> The age of the new user │412+<font color="#A5A5A1">│ [default: None] │</font>413+<font color="#A5A5A1">│ </font><font color="#A1EFE4"><b>--favorite-color</b></font> <font color="#F4BF75"><b>TEXT </b></font> The favorite color of the new │414+<font color="#A5A5A1">│ user │</font>415+<font color="#A5A5A1">│ [default: None] │</font>416+<font color="#A5A5A1">╰───────────────────────────────────────────────────────────────────╯</font>417+```418+419+</div>420+421+And of course, the `rich_help_panel` can be used in the same way for commands in the same application.422+423+And those panels will be shown when you use the main `--help` option.424+425+<div class="termy">426+427+```console428+$ python main.py --help429+430+<b> </b><font color="#F4BF75"><b>Usage: </b></font><b>main.py [OPTIONS] COMMAND [ARGS]... </b>431+<b> </b>432+<font color="#A5A5A1">╭─ Options ─────────────────────────────────────────────────────────╮</font>433+<font color="#A5A5A1">│ </font><font color="#A1EFE4"><b>--install-completion</b></font> Install completion for the current │434+<font color="#A5A5A1">│ shell. │</font>435+<font color="#A5A5A1">│ </font><font color="#A1EFE4"><b>--show-completion</b></font> Show completion for the current │436+<font color="#A5A5A1">│ shell, to copy it or customize the │</font>437+<font color="#A5A5A1">│ installation. │</font>438+<font color="#A5A5A1">│ </font><font color="#A1EFE4"><b>--help</b></font> Show this message and exit. │439+<font color="#A5A5A1">╰───────────────────────────────────────────────────────────────────╯</font>440+<font color="#A5A5A1">╭─ Commands ────────────────────────────────────────────────────────╮</font>441+<font color="#A5A5A1">│ </font><font color="#A1EFE4"><b>create </b></font> <font color="#A6E22E">Create</font> a new user. ✨ │442+<font color="#A5A5A1">╰───────────────────────────────────────────────────────────────────╯</font>443+<font color="#A5A5A1">╭─ Utils and Configs ───────────────────────────────────────────────╮</font>444+<font color="#A5A5A1">│ </font><font color="#A1EFE4"><b>config </b></font> <font color="#66D9EF">Configure</font> the system. 🔧 │445+<font color="#A5A5A1">╰───────────────────────────────────────────────────────────────────╯</font>446+```447+448+</div>449+450+You can see the custom panel for the commands for "`Utils and Configs`".451+452+## Epilog453+454+If you need, you can also add an epilog section to the help of your commands:455+456+```Python hl_lines="6"457+{!../docs_src/commands/help/tutorial008.py!}458+```459+460+And when you check the `--help` option it will look like:461+462+<div class="termy">463+464+```console465+$ python main.py --help466+467+<b> </b><font color="#F4BF75"><b>Usage: </b></font><b>main.py [OPTIONS] USERNAME </b>468+<b> </b>469+ <font color="#A6E22E">Create</font> a new user. ✨470+471+<font color="#A5A5A1">╭─ Arguments ───────────────────────────────────────────────────────╮</font>472+<font color="#A5A5A1">│ </font><font color="#F92672">*</font> username <font color="#F4BF75"><b>TEXT</b></font> [default: None] <font color="#A6194C">[required]</font> │473+<font color="#A5A5A1">╰───────────────────────────────────────────────────────────────────╯</font>474+<font color="#A5A5A1">╭─ Options ─────────────────────────────────────────────────────────╮</font>475+<font color="#A5A5A1">│ </font><font color="#A1EFE4"><b>--install-completion</b></font> Install completion for the current │476+<font color="#A5A5A1">│ shell. │</font>477+<font color="#A5A5A1">│ </font><font color="#A1EFE4"><b>--show-completion</b></font> Show completion for the current │478+<font color="#A5A5A1">│ shell, to copy it or customize the │</font>479+<font color="#A5A5A1">│ installation. │</font>480+<font color="#A5A5A1">│ </font><font color="#A1EFE4"><b>--help</b></font> Show this message and exit. │481+<font color="#A5A5A1">╰───────────────────────────────────────────────────────────────────╯</font>482+483+ Made with ❤ in <font color="#66D9EF">Venus</font>484+```485+486+</div>modified:docs/tutorial/options/autocompletion.md+7 added-4 removed
275 unmodified lines276 If you need a refresher about what is "standard output" and "standard error" check the section in [Printing and Colors: "Standard Output" and "Standard Error"](../printing.md#standard-output-and-standard-error){.internal-link target=_blank}.277 278 The completion system only reads from "standard output", so, printing to "standard error" won't break completion. 🚀279 280-You can print to "standard error" with `typer.echo("some text", err=True)`.280+You can print to "standard error" with a **Rich** `Console(stderr=True)`.281 282-Using `err=True` tells **Typer** (actually Click) that the output should be shown in "standard error".282+Using `stderr=True` tells **Rich** that the output should be shown in "standard error".283 284-```Python hl_lines="12 13"284+```Python hl_lines="12 15-16"285 {!../docs_src/options/autocompletion/tutorial008.py!}286 ```287 288+!!! info289+ If you can't install and use Rich, you can also use `print(lastname, file=sys.stderr)` or `typer.echo("some text", err=True)` instead.290+291 We get all the *CLI parameters* as a raw `list` of `str` by declaring a parameter with type `List[str]`, here it's named `args`.292 293 !!! tip294 Here we name the list of all the raw *CLI parameters* `args` because that's the convention with Click.26 unmodified lines321 ## Getting the Context and the raw *CLI parameters*322 323 Of course, you can declare everything if you need it, the context, the raw *CLI parameters*, and the incomplete `str`:324 322-```Python hl_lines="12"325+```Python hl_lines="15"326 {!../docs_src/options/autocompletion/tutorial009.py!}327 ```328 329 Check it:37 unmodified linesmodified:docs/tutorial/options/help.md+56 added-1 removed
60 unmodified lines61 ```62 63 </div>64 65+## *CLI Options* help panels66+67+The same as with *CLI arguments*, you can put the help for some *CLI options* in different panels to be shown with the `--help` option.68+69+If you have installed Rich as described in the docs for [Printing and Colors](../printing.md){.internal-link target=_blank}, you can set the `rich_help_panel` parameter to the name of the panel you want for each *CLI option*:70+71+```Python hl_lines="8 11"72+{!../docs_src/options/help/tutorial002.py!}73+```74+75+Now, when you check the `--help` option, you will see a default panel named "`Options`" for the *CLI options* that don't have a custom `rich_help_panel`.76+77+And below you will see other panels for the *CLI options* that have a custom panel set in the `rich_help_panel` parameter:78+79+<div class="termy">80+81+```console82+$ python main.py --help83+84+<b> </b><font color="#F4BF75"><b>Usage: </b></font><b>main.py [OPTIONS] NAME </b>85+<b> </b>86+ Say hi to NAME, optionally with a <font color="#A1EFE4"><b>--lastname</b></font>.87+ If <font color="#6B9F98"><b>--formal</b></font><font color="#A5A5A1"> is used, say hi very formally. </font>88+89+<font color="#A5A5A1">╭─ Arguments ───────────────────────────────────────────────────────╮</font>90+<font color="#A5A5A1">│ </font><font color="#F92672">*</font> name <font color="#F4BF75"><b>TEXT</b></font> [default: None] <font color="#A6194C">[required]</font> │91+<font color="#A5A5A1">╰───────────────────────────────────────────────────────────────────╯</font>92+<font color="#A5A5A1">╭─ Options ─────────────────────────────────────────────────────────╮</font>93+<font color="#A5A5A1">│ </font><font color="#A1EFE4"><b>--lastname</b></font> <font color="#F4BF75"><b>TEXT</b></font> Last name of person to greet. │94+<font color="#A5A5A1">│ </font><font color="#A1EFE4"><b>--install-completion</b></font> <font color="#F4BF75"><b> </b></font> Install completion for the │95+<font color="#A5A5A1">│ current shell. │</font>96+<font color="#A5A5A1">│ </font><font color="#A1EFE4"><b>--show-completion</b></font> <font color="#F4BF75"><b> </b></font> Show completion for the current │97+<font color="#A5A5A1">│ shell, to copy it or customize │</font>98+<font color="#A5A5A1">│ the installation. │</font>99+<font color="#A5A5A1">│ </font><font color="#A1EFE4"><b>--help</b></font> <font color="#F4BF75"><b> </b></font> Show this message and exit. │100+<font color="#A5A5A1">╰───────────────────────────────────────────────────────────────────╯</font>101+<font color="#A5A5A1">╭─ Customization and Utils ─────────────────────────────────────────╮</font>102+<font color="#A5A5A1">│ </font><font color="#A1EFE4"><b>--formal</b></font> <font color="#AE81FF"><b>--no-formal</b></font> Say hi formally. │103+<font color="#A5A5A1">│ [default: no-formal] │</font>104+<font color="#A5A5A1">│ </font><font color="#A1EFE4"><b>--debug</b></font> <font color="#AE81FF"><b>--no-debug</b></font> Enable debugging. │105+<font color="#A5A5A1">│ [default: no-debug] │</font>106+<font color="#A5A5A1">╰───────────────────────────────────────────────────────────────────╯</font>107+```108+109+</div>110+111+Here we have a custom *CLI options* panel named "`Customization and Utils`".112+113+## Help with style using Rich114+115+In a future section you will see how to use custom markup in the `help` for *CLI options* when reading about [Commands - Command Help](../commands/help.md#rich-markdown-and-markup){.internal-link target=_blank}.116+117+If you are in a hurry you can jump there, but otherwise, it would be better to continue reading here and following the tutorial in order.118+119+120 ## Hide default from help121 122 You can tell Typer to not show the default value in the help text with `show_default=False`:123 124 ```Python hl_lines="4"70-{!../docs_src/options/help/tutorial002.py!}125+{!../docs_src/options/help/tutorial003.py!}126 ```127 128 And it will no longer show the default value in the help text:129 27 unmodified linesmodified:docs/tutorial/first-steps.md+93 added-62 removed
4 unmodified lines5 ```Python6 {!../docs_src/first_steps/tutorial001.py!}7 ```8 9-!!! tip10- You will learn more about `typer.echo()` later in the docs.11-9 Copy that to a file `main.py`.10 11 Test it:12 8 unmodified lines21 22 // Now check the --help23 $ python main.py --help24 28-Usage: main.py [OPTIONS]29-30-Options:31- --install-completion Install completion for the current shell.32- --show-completion Show completion for the current shell, to copy it or customize the installation.33- --help Show this message and exit.25+<b> </b><font color="#F4BF75"><b>Usage: </b></font><b>main.py [OPTIONS] </b>26+<b> </b>27+<font color="#A5A5A1">╭─ Options ─────────────────────────────────────────╮</font>28+<font color="#A5A5A1">│ </font><font color="#A1EFE4"><b>--install-completion</b></font> Install completion │29+<font color="#A5A5A1">│ for the current │</font>30+<font color="#A5A5A1">│ shell. │</font>31+<font color="#A5A5A1">│ </font><font color="#A1EFE4"><b>--show-completion</b></font> Show completion for │32+<font color="#A5A5A1">│ the current shell, │</font>33+<font color="#A5A5A1">│ to copy it or │</font>34+<font color="#A5A5A1">│ customize the │</font>35+<font color="#A5A5A1">│ installation. │</font>36+<font color="#A5A5A1">│ </font><font color="#A1EFE4"><b>--help</b></font> Show this message │37+<font color="#A5A5A1">│ and exit. │</font>38+<font color="#A5A5A1">╰───────────────────────────────────────────────────╯</font>39 ```40 41 </div>42 36 unmodified lines79 80 $ python main.py81 82 // If you run it without the argument, it shows a nice error78-Usage: main.py [OPTIONS] NAME79-Try "main.py --help" for help.83+<font color="#F4BF75">Usage: </font>main.py [OPTIONS] NAME84+<font color="#A5A5A1">Try </font><font color="#44919F">'main.py </font><font color="#44919F"><b>--help</b></font><font color="#44919F">'</font><font color="#A5A5A1"> for help.</font>85+<font color="#F92672">╭─ Error ───────────────────────────────────────────╮</font>86+<font color="#F92672">│</font> Missing argument 'NAME'. <font color="#F92672">│</font>87+<font color="#F92672">╰───────────────────────────────────────────────────╯</font>88 81-Error: Missing argument 'NAME'.82-89 // Now pass that NAME CLI argument90 $ python main.py Camila91 92 Hello Camila26 unmodified lines119 ```console120 // Check the main --help121 $ python main.py --help122 117-Usage: main.py [OPTIONS] NAME LASTNAME123+<font color="#F4BF75">Usage: </font>main.py [OPTIONS] NAME124+<font color="#A5A5A1">Try </font><font color="#44919F">'main.py </font><font color="#44919F"><b>--help</b></font><font color="#44919F">'</font><font color="#A5A5A1"> for help.</font>125+<font color="#F92672">╭─ Error ───────────────────────────────────────────╮</font>126+<font color="#F92672">│</font> Missing argument 'NAME'. <font color="#F92672">│</font>127+<font color="#F92672">╰───────────────────────────────────────────────────╯</font>128 119-Arguments:120- NAME [required]121- LASTNAME [required]129+<font color="#A1EFE4"><b>typer</b></font> on <font color="#AE81FF"><b> richify</b></font> <font color="#F92672"><b>[»!?] </b></font>via <font color="#F4BF75"><b>🐍 v3.7.5 (env3.7)</b></font>130+<font color="#F92672"><b>❯</b></font> <font color="#A6E22E">python</font> <u style="text-decoration-style:single">main.py</u>131+<font color="#F4BF75">Usage: </font>main.py [OPTIONS] NAME LASTNAME132+<font color="#A5A5A1">Try </font><font color="#44919F">'main.py </font><font color="#44919F"><b>--help</b></font><font color="#44919F">'</font><font color="#A5A5A1"> for help.</font>133+<font color="#F92672">╭─ Error ───────────────────────────────────────────╮</font>134+<font color="#F92672">│</font> Missing argument 'NAME'. <font color="#F92672">│</font>135+<font color="#F92672">╰───────────────────────────────────────────────────╯</font>136 123-Options:124- --install-completion Install completion for the current shell.125- --show-completion Show completion for the current shell, to copy it or customize the installation.126- --help Show this message and exit.127-137 // There are now 2 CLI arguments, name and lastname138 139 // Now pass a single name argument140 $ python main.py Camila141 133-Usage: main.py [OPTIONS] NAME LASTNAME134-Try "main.py --help" for help.142+<font color="#F4BF75">Usage: </font>main.py [OPTIONS] NAME LASTNAME143+<font color="#A5A5A1">Try </font><font color="#44919F">'main.py </font><font color="#44919F"><b>--help</b></font><font color="#44919F">'</font><font color="#A5A5A1"> for help.</font>144+<font color="#F92672">╭─ Error ───────────────────────────────────────────╮</font>145+<font color="#F92672">│</font> Missing argument 'LASTNAME'. <font color="#F92672">│</font>146+<font color="#F92672">╰───────────────────────────────────────────────────╯</font>147 136-Error: Missing argument 'LASTNAME'.137-148 // These 2 arguments are required, so, pass both:149 $ python main.py Camila Gutiérrez150 151 Hello Camila Gutiérrez90 unmodified lines242 ```console243 // Get the help244 $ python main.py --help245 236-Usage: main.py [OPTIONS] NAME LASTNAME237-238-Arguments:239- NAME [required]240- LASTNAME [required]241-242-Options:243- --formal / --no-formal [default: False]244- --install-completion Install completion for the current shell.245- --show-completion Show completion for the current shell, to copy it or customize the installation.246- --help Show this message and exit.246+<b> </b><font color="#F4BF75"><b>Usage: </b></font><b>main.py [OPTIONS] NAME LASTNAME </b>247+<b> </b>248+<font color="#A5A5A1">╭─ Arguments ─────────────────────────────────────────────────────╮</font>249+<font color="#A5A5A1">│ </font><font color="#F92672">*</font> name <font color="#F4BF75"><b>TEXT</b></font> [default: None] <font color="#A6194C">[required]</font> │250+<font color="#A5A5A1">│ </font><font color="#F92672">*</font> lastname <font color="#F4BF75"><b>TEXT</b></font> [default: None] <font color="#A6194C">[required]</font> │251+<font color="#A5A5A1">╰─────────────────────────────────────────────────────────────────╯</font>252+<font color="#A5A5A1">╭─ Options ───────────────────────────────────────────────────────╮</font>253+<font color="#A5A5A1">│ </font><font color="#A1EFE4"><b>--formal</b></font> <font color="#AE81FF"><b>--no-formal</b></font> [default: no-formal] │254+<font color="#A5A5A1">│ </font><font color="#A1EFE4"><b>--install-completion</b></font> Install completion for │255+<font color="#A5A5A1">│ the current shell. │</font>256+<font color="#A5A5A1">│ </font><font color="#A1EFE4"><b>--show-completion</b></font> Show completion for │257+<font color="#A5A5A1">│ the current shell, to │</font>258+<font color="#A5A5A1">│ copy it or customize │</font>259+<font color="#A5A5A1">│ the installation. │</font>260+<font color="#A5A5A1">│ </font><font color="#A1EFE4"><b>--help</b></font> Show this message and │261+<font color="#A5A5A1">│ exit. │</font>262+<font color="#A5A5A1">╰─────────────────────────────────────────────────────────────────╯</font>263 ```264 265 </div>266 40 unmodified lines307 308 ```console309 $ python main.py --help310 295-Usage: main.py [OPTIONS] NAME296-297-Arguments:298- NAME [required]299-300-Options:301- --lastname TEXT [default: ]302- --formal / --no-formal [default: False]303- --install-completion Install completion for the current shell.304- --show-completion Show completion for the current shell, to copy it or customize the installation.305- --help Show this message and exit.311+<b> </b><font color="#F4BF75"><b>Usage: </b></font><b>main.py [OPTIONS] NAME </b>312+<b> </b>313+<font color="#A5A5A1">╭─ Arguments ───────────────────────────────────────────────────────╮</font>314+<font color="#A5A5A1">│ </font><font color="#F92672">*</font> name <font color="#F4BF75"><b>TEXT</b></font> [default: None] <font color="#A6194C">[required]</font> │315+<font color="#A5A5A1">╰───────────────────────────────────────────────────────────────────╯</font>316+<font color="#A5A5A1">╭─ Options ─────────────────────────────────────────────────────────╮</font>317+<font color="#A5A5A1">│ </font><font color="#A1EFE4"><b>--lastname</b></font> <font color="#F4BF75"><b>TEXT</b></font> │318+<font color="#A5A5A1">│ </font><font color="#A1EFE4"><b>--formal</b></font> <font color="#AE81FF"><b>--no-formal</b></font> <font color="#F4BF75"><b> </b></font> [default: no-formal] │319+<font color="#A5A5A1">│ </font><font color="#A1EFE4"><b>--install-completion</b></font> <font color="#F4BF75"><b> </b></font> Install completion │320+<font color="#A5A5A1">│ for the current │</font>321+<font color="#A5A5A1">│ shell. │</font>322+<font color="#A5A5A1">│ </font><font color="#A1EFE4"><b>--show-completion</b></font> <font color="#F4BF75"><b> </b></font> Show completion for │323+<font color="#A5A5A1">│ the current shell, │</font>324+<font color="#A5A5A1">│ to copy it or │</font>325+<font color="#A5A5A1">│ customize the │</font>326+<font color="#A5A5A1">│ installation. │</font>327+<font color="#A5A5A1">│ </font><font color="#A1EFE4"><b>--help</b></font> <font color="#F4BF75"><b> </b></font> Show this message │328+<font color="#A5A5A1">│ and exit. │</font>329+<font color="#A5A5A1">╰───────────────────────────────────────────────────────────────────╯</font>330 ```331 332 </div>333 48 unmodified lines382 383 ```console384 $ python main.py --help385 362-Usage: main.py [OPTIONS] NAME386+<b> </b><font color="#F4BF75"><b>Usage: </b></font><b>main.py [OPTIONS] NAME </b>387+<b> </b>388+ Say hi to NAME, optionally with a <font color="#A1EFE4"><b>--lastname</b></font>.389+ If <font color="#6B9F98"><b>--formal</b></font><font color="#A5A5A1"> is used, say hi very formally. </font>390 364- Say hi to NAME, optionally with a --lastname.365-366- If --formal is used, say hi very formally.367-368-Arguments:369- NAME [required]370-371-Options:372- --lastname TEXT [default: ]373- --formal / --no-formal [default: False]374- --install-completion Install completion for the current shell.375- --show-completion Show completion for the current shell, to copy it or customize the installation.376- --help Show this message and exit.391+<font color="#A5A5A1">╭─ Arguments ───────────────────────────────────────────────────────╮</font>392+<font color="#A5A5A1">│ </font><font color="#F92672">*</font> name <font color="#F4BF75"><b>TEXT</b></font> [default: None] <font color="#A6194C">[required]</font> │393+<font color="#A5A5A1">╰───────────────────────────────────────────────────────────────────╯</font>394+<font color="#A5A5A1">╭─ Options ─────────────────────────────────────────────────────────╮</font>395+<font color="#A5A5A1">│ </font><font color="#A1EFE4"><b>--lastname</b></font> <font color="#F4BF75"><b>TEXT</b></font> │396+<font color="#A5A5A1">│ </font><font color="#A1EFE4"><b>--formal</b></font> <font color="#AE81FF"><b>--no-formal</b></font> <font color="#F4BF75"><b> </b></font> [default: no-formal] │397+<font color="#A5A5A1">│ </font><font color="#A1EFE4"><b>--install-completion</b></font> <font color="#F4BF75"><b> </b></font> Install completion │398+<font color="#A5A5A1">│ for the current │</font>399+<font color="#A5A5A1">│ shell. │</font>400+<font color="#A5A5A1">│ </font><font color="#A1EFE4"><b>--show-completion</b></font> <font color="#F4BF75"><b> </b></font> Show completion for │401+<font color="#A5A5A1">│ the current shell, │</font>402+<font color="#A5A5A1">│ to copy it or │</font>403+<font color="#A5A5A1">│ customize the │</font>404+<font color="#A5A5A1">│ installation. │</font>405+<font color="#A5A5A1">│ </font><font color="#A1EFE4"><b>--help</b></font> <font color="#F4BF75"><b> </b></font> Show this message │406+<font color="#A5A5A1">│ and exit. │</font>407+<font color="#A5A5A1">╰───────────────────────────────────────────────────────────────────╯</font>408 ```409 410 </div>411 111 unmodified linesmodified:docs/tutorial/index.md+3 added-3 removed
66 unmodified lines67686970717172737374757677787866 unmodified lines
<div class="termy">
```console$ pip install typer[all]$ pip install "typer[all]"---> 100%Successfully installed typer click colorama shellingham richSuccessfully installed typer click shellingham rich```
</div>
...that also includes `colorama`, `shellingham`, and `rich`....that also includes `rich` and `shellingham`.modified:docs/tutorial/printing.md+196 added-49 removed
1-You can use `typer.echo()` to print to the screen:1+You can use the normal `print()` to show information on the screen:2 3 ```Python hl_lines="5"4 {!../docs_src/first_steps/tutorial001.py!}5 ```6 7-The reason to use `typer.echo()` instead of just `print()` is that it applies some error corrections in case the terminal is misconfigured, and it will properly output color if it's supported.7+It will show the output normally:8 9-!!! info10- `typer.echo()` comes directly from Click, you can read more about it in <a href="https://click.palletsprojects.com/en/7.x/quickstart/#echoing" class="external-link" target="_blank">Click's docs</a>.11-12-Check it:13-9 <div class="termy">10 11 ```console12 $ python main.py2 unmodified lines15 ```16 17 </div>18 24-## Color19+## Use Rich20 26-!!! info27- For colors to work correctly on Windows you need to also install <a href="https://pypi.org/project/colorama/" class="external-link" target="_blank">`colorama`</a>.21+You can also display beautiful and more complex information using <a href="https://rich.readthedocs.io/" class="external-link" target="_blank">Rich</a>.22 29- You don't need to call `colorama.init()`. Typer (actually Click) will handle it underneath.23+### Install Rich24 31- And make sure you use `typer.echo()` instead of `print()`.25+First, you need to install it:26 33-!!! note "Technical Details"34- The way color works in terminals is by using some codes (ANSI escape sequences) as part of the text.27+<div class="termy">28 36- So, a colored text is still just a `str`.29+```console30+// Rich comes with typer[all]31+$ pip install "typer[all]"32+---> 100%33+Successfully installed typer rich34 38-You can create colored strings to output to the terminal with `typer.style()`, that gives you `str`s that you can then pass to `typer.echo()`:35+// Alternatively, you can install Rich independently36+$ pip install rich37+---> 100%38+Successfully installed rich39+```40 41+</div>42+43+### Use Rich `print`44+45+For the simplest cases, you can just import `print` from `rich` and use it instead of the standard `print`:46+40-```Python hl_lines="7 9"47+```Python hl_lines="2 15"48 {!../docs_src/printing/tutorial001.py!}49 ```50 44-!!! tip45- The parameters `fg` and `bg` receive strings with the color names for the "**f**ore**g**round" and "**b**ack**g**round" colors. You could simply pass `fg="green"` and `bg="red"`.51+Just with that, **Rich** will be able to print your data with nice colors and structure:52 47- But **Typer** provides them all as variables like `typer.colors.GREEN` just so you can use autocompletion while selecting them.53+<div class="termy">54 49-Check it:55+```console56+$ python main.py57 51-<div class="use-termynal" data-termynal>52-<span data-ty="input">python main.py</span>53-<span data-ty>everything is <span style="color: green; font-weight: bold;">good</span></span>54-<span data-ty="input">python main.py --no-good</span>55-<span data-ty>everything is <span style="color: white; background-color: red;">bad</span></span>58+Here's the data59+<b>{</b>60+ <font color="#A6E22E">'name'</font>: <font color="#A6E22E">'Rick'</font>,61+ <font color="#A6E22E">'age'</font>: <font color="#A1EFE4"><b>42</b></font>,62+ <font color="#A6E22E">'items'</font>: <b>[</b>63+ <b>{</b><font color="#A6E22E">'name'</font>: <font color="#A6E22E">'Portal Gun'</font><b>}</b>,64+ <b>{</b><font color="#A6E22E">'name'</font>: <font color="#A6E22E">'Plumbus'</font><b>}</b>65+ <b>]</b>,66+ <font color="#A6E22E">'active'</font>: <font color="#A6E22E"><i>True</i></font>,67+ <font color="#A6E22E">'affiliation'</font>: <font color="#AE81FF"><i>None</i></font>68+<b>}</b>69+```70+71 </div>72 58-You can pass these function arguments to `typer.style()`:73+### Rich Markup74 60-* `fg`: the foreground color.61-* `bg`: the background color.62-* `bold`: enable or disable bold mode.63-* `dim`: enable or disable dim mode. This is badly supported.64-* `underline`: enable or disable underline.65-* `blink`: enable or disable blinking.66-* `reverse`: enable or disable inverse rendering (foreground becomes background and the other way round).67-* `reset`: by default a reset-all code is added at the end of the string which means that styles do not carry over. This can be disabled to compose styles.75+Rich also supports a <a href="https://rich.readthedocs.io/en/stable/markup.html" class="external-link" target="_blank">custom markup syntax</a> to set colors and styles, for example:76 69-!!! info70- You can read more about it in <a href="https://click.palletsprojects.com/en/7.x/api/#click.style" class="external-link" target="_blank">Click's docs about `style()`</a>77+```Python hl_lines="6"78+{!../docs_src/printing/tutorial002.py!}79+```80 72-## `typer.secho()` - style and print81+<div class="termy">82 74-There's a shorter form to style and print at the same time with `typer.secho()` it's like `typer.echo()` but also adds style like `typer.style()`:83+```console84+$ python main.py85 76-```Python hl_lines="5"77-{!../docs_src/printing/tutorial002.py!}86+<font color="#F92672"><b>Alert!</b></font> <font color="#A6E22E">Portal gun</font> shooting! 💥87 ```88 80-Check it:89+</div>90 82-<div class="use-termynal" data-termynal>83-<span data-ty="input">python main.py Camila</span>84-<span style="color: magenta;" data-ty>Welcome here Camila</span>91+In this example you can see how to use font styles, colors, and even emojis.92+93+To learn more check out the <a href="https://rich.readthedocs.io/en/stable/markup.html" class="external-link" target="_blank">Rich docs</a>.94+95+### Rich Tables96+97+The way Rich works internally is that it uses a `Console` object to display the information.98+99+When you call Rich's `print`, it automatically creates this object and uses it.100+101+But for advanced use cases, you could create a `Console` yourself.102+103+```Python hl_lines="2-3 5 9-12"104+{!../docs_src/printing/tutorial003.py!}105+```106+107+In this example, we create a `Console`, and a `Table`. And then we can add some rows to the table, and print it.108+109+If you run it, you will see a nicely formatted table:110+111+<div class="termy">112+113+```console114+$ python main.py115+116+┏━━━━━━━┳━━━━━━━━━━━━┓117+┃<b> Name </b>┃<b> Item </b>┃118+┡━━━━━━━╇━━━━━━━━━━━━┩119+│ Rick │ Portal Gun │120+│ Morty │ Plumbus │121+└───────┴────────────┘122+```123+124 </div>125 126+Rich has many other features, as an example, you can check the docs for:127+128+* <a href="https://rich.readthedocs.io/en/stable/prompt.html" class="external-link" target="_blank">Prompt</a>129+* <a href="https://rich.readthedocs.io/en/stable/markdown.html" class="external-link" target="_blank">Markdown</a>130+* <a href="https://rich.readthedocs.io/en/stable/panel.html" class="external-link" target="_blank">Panel</a>131+* ...and more.132+133+### Typer and Rich134+135+If you are wondering what tool should be used for what, **Typer** is useful for structuring the command line application, with options, arguments, subcommands, data validation, etc.136+137+In general, **Typer** tends to be the entry point to your program, taking the first input from the user.138+139+**Rich** is useful for the parts that need to *display* information. Showing beautiful content on the screen.140+141+The best results for your command line application would be achieved combining both **Typer** and **Rich**.142+143 ## "Standard Output" and "Standard Error"144 145 The way printing works underneath is that the **operating system** (Linux, Windows, macOS) treats what we print as if our CLI program was **writing text** to a "**virtual file**" called "**standard output**".146 17 unmodified lines164 But it will work normally in Bash, Zsh, and Fish.165 166 ### Printing to "standard error"167 112-You can print to "standard error" with `typer.echo("some text", err=True)`.168+You can print to "standard error" creating a Rich `Console` with `stderr=True`.169 114-Using `err=True` tells **Typer** (actually Click) that the output should be shown in "standard error".170+!!! tip171+ `stderr` is short for "standard error".172 173+Using `stderr=True` tells **Rich** that the output should be shown in "standard error".174+116-```Python hl_lines="5"117-{!../docs_src/printing/tutorial003.py!}175+```Python hl_lines="4 8"176+{!../docs_src/printing/tutorial004.py!}177 ```178 179 When you try it in the terminal, it will probably just look the same:180 17 unmodified lines198 199 Right now this probably seems quite useless 🤷♂.200 201 But understanding that will come handy in the future, for example for autocompletion and testing.202+203+## Typer Echo204+205+!!! warning206+ In most of the cases, for displaying advanced information, it is recommended to use <a href="https://rich.readthedocs.io/" class="external-link" target="_blank">Rich</a>.207+208+ You can probably skip the rest of this section. 🎉😎209+210+**Typer** also has a small utility `typer.echo()` to print information on the screen, it comes directly from Click. But normally you shouldn't need it.211+212+For the simplest cases, you can use the standard Python `print()`.213+214+And for the cases where you want to display data more beautifully, or more advanced content, you should use **Rich** instead.215+216+### Why `typer.echo`217+218+`typer.echo()` (which is actually just `click.echo()`) applies some checks to try and convert binary data to strings, and other similar things.219+220+But in most of the cases you wouldn't need it, as in modern Python strings (`str`) already support and use Unicode, and you would rarely deal with pure `bytes` that you want to print on the screen.221+222+If you have some `bytes` objects, you would probably want to decode them intentionally and directly before trying to print them.223+224+And if you want to print data with colors and other features, you are much better off with the more advanced tools in **Rich**.225+226+!!! info227+ `typer.echo()` comes directly from Click, you can read more about it in <a href="https://click.palletsprojects.com/en/7.x/quickstart/#echoing" class="external-link" target="_blank">Click's docs</a>.228+229+### Color230+231+!!! note "Technical Details"232+ The way color works in terminals is by using some codes (ANSI escape sequences) as part of the text.233+234+ So, a colored text is still just a `str`.235+236+!!! tip237+ Again, you are much better off using <a href="https://rich.readthedocs.io/" class="external-link" target="_blank">Rich</a> for this. 😎238+239+You can create colored strings to output to the terminal with `typer.style()`, that gives you `str`s that you can then pass to `typer.echo()`:240+241+```Python hl_lines="7 9"242+{!../docs_src/printing/tutorial005.py!}243+```244+245+!!! tip246+ The parameters `fg` and `bg` receive strings with the color names for the "**f**ore**g**round" and "**b**ack**g**round" colors. You could simply pass `fg="green"` and `bg="red"`.247+248+ But **Typer** provides them all as variables like `typer.colors.GREEN` just so you can use autocompletion while selecting them.249+250+Check it:251+252+<div class="use-termynal" data-termynal>253+<span data-ty="input">python main.py</span>254+<span data-ty>everything is <span style="color: green; font-weight: bold;">good</span></span>255+<span data-ty="input">python main.py --no-good</span>256+<span data-ty>everything is <span style="color: white; background-color: red;">bad</span></span>257+</div>258+259+You can pass these function arguments to `typer.style()`:260+261+* `fg`: the foreground color.262+* `bg`: the background color.263+* `bold`: enable or disable bold mode.264+* `dim`: enable or disable dim mode. This is badly supported.265+* `underline`: enable or disable underline.266+* `blink`: enable or disable blinking.267+* `reverse`: enable or disable inverse rendering (foreground becomes background and the other way round).268+* `reset`: by default a reset-all code is added at the end of the string which means that styles do not carry over. This can be disabled to compose styles.269+270+!!! info271+ You can read more about it in <a href="https://click.palletsprojects.com/en/7.x/api/#click.style" class="external-link" target="_blank">Click's docs about `style()`</a>272+273+### `typer.secho()` - style and print274+275+!!! tip276+ In case you didn't see above, you are much better off using <a href="https://rich.readthedocs.io/" class="external-link" target="_blank">Rich</a> for this. 😎277+278+There's a shorter form to style and print at the same time with `typer.secho()` it's like `typer.echo()` but also adds style like `typer.style()`:279+280+```Python hl_lines="5"281+{!../docs_src/printing/tutorial006.py!}282+```283+284+Check it:285+286+<div class="use-termynal" data-termynal>287+<span data-ty="input">python main.py Camila</span>288+<span style="color: magenta;" data-ty>Welcome here Camila</span>289+</div>modified:docs/index.md+88 added-59 removed
54 unmodified lines55 56 <div class="termy">57 58 ```console59-$ pip install typer59+$ pip install "typer[all]"60 ---> 100%61 Successfully installed typer62 ```63 64 </div>65 66+**Note**: that will include <a href="https://rich.readthedocs.io/" class="external-link" target="_blank">Rich</a>. Rich is the recommended library to *display* information on the terminal, it is optional, but when installed, it's deeply integrated into **Typer** to display beautiful output.67+68 ## Example69 70 ### The absolute minimum71 3 unmodified lines75 import typer76 77 78 def main(name: str):77- typer.echo(f"Hello {name}")79+ print(f"Hello {name}")80 81 82 if __name__ == "__main__":83 typer.run(main)9 unmodified lines93 // Run your application94 $ python main.py95 96 // You get a nice error, you are missing NAME95-Usage: main.py [OPTIONS] NAME96-Try "main.py --help" for help.97+<font color="#F4BF75">Usage: </font>main.py [OPTIONS] NAME98+<font color="#A5A5A1">Try </font><font color="#44919F">'main.py </font><font color="#44919F"><b>--help</b></font><font color="#44919F">'</font><font color="#A5A5A1"> for help.</font>99+<font color="#F92672">╭─ Error ───────────────────────────────────────────╮</font>100+<font color="#F92672">│</font> Missing argument 'NAME'. <font color="#F92672">│</font>101+<font color="#F92672">╰───────────────────────────────────────────────────╯</font>102 98-Error: Missing argument 'NAME'.103 104 // You get a --help for free105 $ python main.py --help106 103-Usage: main.py [OPTIONS] NAME107+<b> </b><font color="#F4BF75"><b>Usage: </b></font><b>main.py [OPTIONS] NAME </b>108+<b> </b>109+<font color="#A5A5A1">╭─ Arguments ───────────────────────────────────────╮</font>110+<font color="#A5A5A1">│ </font><font color="#F92672">*</font> name <font color="#F4BF75"><b>TEXT</b></font> [default: None] <font color="#A6194C">[required]</font> │111+<font color="#A5A5A1">╰───────────────────────────────────────────────────╯</font>112+<font color="#A5A5A1">╭─ Options ─────────────────────────────────────────╮</font>113+<font color="#A5A5A1">│ </font><font color="#A1EFE4"><b>--install-completion</b></font> Install completion │114+<font color="#A5A5A1">│ for the current │</font>115+<font color="#A5A5A1">│ shell. │</font>116+<font color="#A5A5A1">│ </font><font color="#A1EFE4"><b>--show-completion</b></font> Show completion for │117+<font color="#A5A5A1">│ the current shell, │</font>118+<font color="#A5A5A1">│ to copy it or │</font>119+<font color="#A5A5A1">│ customize the │</font>120+<font color="#A5A5A1">│ installation. │</font>121+<font color="#A5A5A1">│ </font><font color="#A1EFE4"><b>--help</b></font> Show this message │122+<font color="#A5A5A1">│ and exit. │</font>123+<font color="#A5A5A1">╰───────────────────────────────────────────────────╯</font>124 105-Arguments:106- NAME [required]107-108-Options:109- --install-completion Install completion for the current shell.110- --show-completion Show completion for the current shell, to copy it or customize the installation.111- --help Show this message and exit.112-125 // When you create a package you get ✨ auto-completion ✨ for free, installed with --install-completion126 127 // Now pass the NAME argument128 $ python main.py Camila26 unmodified lines155 156 157 @app.command()158 def hello(name: str):147- typer.echo(f"Hello {name}")159+ print(f"Hello {name}")160 161 162 @app.command()163 def goodbye(name: str, formal: bool = False):164 if formal:153- typer.echo(f"Goodbye Ms. {name}. Have a good day.")165+ print(f"Goodbye Ms. {name}. Have a good day.")166 else:155- typer.echo(f"Bye {name}!")167+ print(f"Bye {name}!")168 169 170 if __name__ == "__main__":171 app()7 unmodified lines179 * Execute the `app()` itself, as if it was a function (instead of `typer.run`).180 181 ### Run the upgraded example182 183+Check the new help:184+185 <div class="termy">186 187 ```console174-// Check the --help188 $ python main.py --help189 177-Usage: main.py [OPTIONS] COMMAND [ARGS]...190+<b> </b><font color="#F4BF75"><b>Usage: </b></font><b>main.py [OPTIONS] COMMAND [ARGS]... </b>191+<b> </b>192+<font color="#A5A5A1">╭─ Options ─────────────────────────────────────────╮</font>193+<font color="#A5A5A1">│ </font><font color="#A1EFE4"><b>--install-completion</b></font> Install completion │194+<font color="#A5A5A1">│ for the current │</font>195+<font color="#A5A5A1">│ shell. │</font>196+<font color="#A5A5A1">│ </font><font color="#A1EFE4"><b>--show-completion</b></font> Show completion for │197+<font color="#A5A5A1">│ the current shell, │</font>198+<font color="#A5A5A1">│ to copy it or │</font>199+<font color="#A5A5A1">│ customize the │</font>200+<font color="#A5A5A1">│ installation. │</font>201+<font color="#A5A5A1">│ </font><font color="#A1EFE4"><b>--help</b></font> Show this message │202+<font color="#A5A5A1">│ and exit. │</font>203+<font color="#A5A5A1">╰───────────────────────────────────────────────────╯</font>204+<font color="#A5A5A1">╭─ Commands ────────────────────────────────────────╮</font>205+<font color="#A5A5A1">│ </font><font color="#A1EFE4"><b>goodbye </b></font> │206+<font color="#A5A5A1">│ </font><font color="#A1EFE4"><b>hello </b></font> │207+<font color="#A5A5A1">╰───────────────────────────────────────────────────╯</font>208 179-Options:180- --install-completion Install completion for the current shell.181- --show-completion Show completion for the current shell, to copy it or customize the installation.182- --help Show this message and exit.209+// You have 2 subcommands (the 2 functions): goodbye and hello210+```211 184-Commands:185- goodbye186- hello212+</div>213 188-// You have 2 subcommands (the 2 functions): goodbye and hello214+Now check the help for the `hello` command:215 190-// Now get the --help for hello216+<div class="termy">217 218+```console219 $ python main.py hello --help220 194-Usage: main.py hello [OPTIONS] NAME221+<b> </b><font color="#F4BF75"><b>Usage: </b></font><b>main.py hello [OPTIONS] NAME </b>222+<b> </b>223+<font color="#A5A5A1">╭─ Arguments ───────────────────────────────────────╮</font>224+<font color="#A5A5A1">│ </font><font color="#F92672">*</font> name <font color="#F4BF75"><b>TEXT</b></font> [default: None] <font color="#A6194C">[required]</font> │225+<font color="#A5A5A1">╰───────────────────────────────────────────────────╯</font>226+<font color="#A5A5A1">╭─ Options ─────────────────────────────────────────╮</font>227+<font color="#A5A5A1">│ </font><font color="#A1EFE4"><b>--help</b></font> Show this message and exit. │228+<font color="#A5A5A1">╰───────────────────────────────────────────────────╯</font>229+```230 196-Arguments:197- NAME [required]231+</div>232 199-Options:200- --help Show this message and exit.233+And now check the help for the `goodbye` command:234 202-// And now get the --help for goodbye235+<div class="termy">236 237+```console238 $ python main.py goodbye --help239 206-Usage: main.py goodbye [OPTIONS] NAME240+<b> </b><font color="#F4BF75"><b>Usage: </b></font><b>main.py goodbye [OPTIONS] NAME </b>241+<b> </b>242+<font color="#A5A5A1">╭─ Arguments ───────────────────────────────────────╮</font>243+<font color="#A5A5A1">│ </font><font color="#F92672">*</font> name <font color="#F4BF75"><b>TEXT</b></font> [default: None] <font color="#A6194C">[required]</font> │244+<font color="#A5A5A1">╰───────────────────────────────────────────────────╯</font>245+<font color="#A5A5A1">╭─ Options ─────────────────────────────────────────╮</font>246+<font color="#A5A5A1">│ </font><font color="#A1EFE4"><b>--formal</b></font> <font color="#AE81FF"><b>--no-formal</b></font> [default: no-formal] │247+<font color="#A5A5A1">│ </font><font color="#A1EFE4"><b>--help</b></font> Show this message │248+<font color="#A5A5A1">│ and exit. │</font>249+<font color="#A5A5A1">╰───────────────────────────────────────────────────╯</font>250 208-Arguments:209- NAME [required]251+// Automatic --formal and --no-formal for the bool option 🎉252+```253 211-Options:212- --formal / --no-formal [default: False]213- --help Show this message and exit.254+</div>255 215-// Automatic --formal and --no-formal for the bool option 🎉256+Now you can try out the new command line application:257 217-// And if you use it with the hello command258+<div class="termy">259 260+```console261+// Use it with the hello command262+263 $ python main.py hello Camila264 265 Hello Camila266 47 unmodified lines314 Typer uses <a href="https://click.palletsprojects.com/" class="external-link" target="_blank">Click</a> internally. That's the only dependency.315 316 But you can also install extras:317 274-* <a href="https://rich.readthedocs.io/en/stable/index.html" class="external-link" target="_blank">Rich</a>: and Typer will show nicely formatted errors automatically.275-* <a href="https://pypi.org/project/colorama/" class="external-link" target="_blank"><code>colorama</code></a>: and Click will automatically use it to make sure your terminal's colors always work correctly, even in Windows.276- * Then you can use any tool you want to output your terminal's colors in all the systems, including the integrated `typer.style()` and `typer.secho()` (provided by Click).277- * Or any other tool, e.g. <a href="https://pypi.org/project/wasabi/" class="external-link" target="_blank"><code>wasabi</code></a>, <a href="https://github.com/erikrose/blessings" class="external-link" target="_blank"><code>blessings</code></a>.318+* <a href="https://rich.readthedocs.io/en/stable/index.html" class="external-link" target="_blank"><code>rich</code></a>: and Typer will show nicely formatted errors automatically.319 * <a href="https://github.com/sarugaku/shellingham" class="external-link" target="_blank"><code>shellingham</code></a>: and Typer will automatically detect the current shell when installing completion.320 * With `shellingham` you can just use `--install-completion`.321 * Without `shellingham`, you have to pass the name of the shell to install completion for, e.g. `--install-completion bash`.322 282-You can install `typer` with `colorama` and `shellingham` with `pip install typer[all]`.323+You can install `typer` with `rich` and `shellingham` with `pip install typer[all]`.324 284-## Other tools and plug-ins285-286-Click has many plug-ins available that you can use. And there are many tools that help with command line applications that you can use as well, even if they are not related to Typer or Click.287-288-For example:289-290-* <a href="https://github.com/click-contrib/click-spinner" class="external-link" target="_blank"><code>click-spinner</code></a>: to show the user that you are loading data. A Click plug-in.291- * There are several other Click plug-ins at <a href="https://github.com/click-contrib" class="external-link" target="_blank">click-contrib</a> that you can explore.292-* <a href="https://pypi.org/project/tabulate/" class="external-link" target="_blank"><code>tabulate</code></a>: to automatically display tabular data nicely. Independent of Click or Typer.293-* <a href="https://github.com/tqdm/tqdm" class="external-link" target="_blank"><code>tqdm</code></a>: a fast, extensible progress bar, alternative to Typer's own `typer.progressbar()`.294-* etc... you can re-use many of the great available tools for building CLIs.295-325 ## License326 327 This project is licensed under the terms of the MIT license.modified:docs_src/app_dir/tutorial001.py+1 added-1 removed
7 unmodified lines8 def main():9 app_dir = typer.get_app_dir(APP_NAME)10 config_path: Path = Path(app_dir) / "config.json"11 if not config_path.is_file():12- typer.echo("Config file doesn't exist yet")12+ print("Config file doesn't exist yet")13 14 15 if __name__ == "__main__":16 typer.run(main)modified:docs_src/arguments/default/tutorial001.py+1 added-1 removed
1 import typer2 3 4 def main(name: str = typer.Argument("Wade Wilson")):5- typer.echo(f"Hello {name}")5+ print(f"Hello {name}")6 7 8 if __name__ == "__main__":9 typer.run(main)modified:docs_src/arguments/default/tutorial002.py+1 added-1 removed
6 unmodified lines7 return random.choice(["Deadpool", "Rick", "Morty", "Hiro"])8 9 10 def main(name: str = typer.Argument(get_name)):11- typer.echo(f"Hello {name}")11+ print(f"Hello {name}")12 13 14 if __name__ == "__main__":15 typer.run(main)modified:docs_src/arguments/envvar/tutorial001.py+1 added-1 removed
1 import typer2 3 4 def main(name: str = typer.Argument("World", envvar="AWESOME_NAME")):5- typer.echo(f"Hello Mr. {name}")5+ print(f"Hello Mr. {name}")6 7 8 if __name__ == "__main__":9 typer.run(main)modified:docs_src/arguments/envvar/tutorial002.py+1 added-1 removed
1 import typer2 3 4 def main(name: str = typer.Argument("World", envvar=["AWESOME_NAME", "GOD_NAME"])):5- typer.echo(f"Hello Mr. {name}")5+ print(f"Hello Mr. {name}")6 7 8 if __name__ == "__main__":9 typer.run(main)modified:docs_src/arguments/envvar/tutorial003.py+1 added-1 removed
1 import typer2 3 4 def main(name: str = typer.Argument("World", envvar="AWESOME_NAME", show_envvar=False)):5- typer.echo(f"Hello Mr. {name}")5+ print(f"Hello Mr. {name}")6 7 8 if __name__ == "__main__":9 typer.run(main)modified:docs_src/arguments/help/tutorial001.py+1 added-1 removed
1 import typer2 3 4 def main(name: str = typer.Argument(..., help="The name of the user to greet")):5- typer.echo(f"Hello {name}")5+ print(f"Hello {name}")6 7 8 if __name__ == "__main__":9 typer.run(main)modified:docs_src/arguments/help/tutorial002.py+1 added-1 removed
3 unmodified lines4 def main(name: str = typer.Argument(..., help="The name of the user to greet")):5 """6 Say hi to NAME very gently, like Dirk.7 """8- typer.echo(f"Hello {name}")8+ print(f"Hello {name}")9 10 11 if __name__ == "__main__":12 typer.run(main)modified:docs_src/arguments/help/tutorial003.py+1 added-1 removed
3 unmodified lines4 def main(name: str = typer.Argument("World", help="Who to greet")):5 """6 Say hi to NAME very gently, like Dirk.7 """8- typer.echo(f"Hello {name}")8+ print(f"Hello {name}")9 10 11 if __name__ == "__main__":12 typer.run(main)modified:docs_src/arguments/help/tutorial004.py+1 added-1 removed
3 unmodified lines4 def main(name: str = typer.Argument("World", help="Who to greet", show_default=False)):5 """6 Say hi to NAME very gently, like Dirk.7 """8- typer.echo(f"Hello {name}")8+ print(f"Hello {name}")9 10 11 if __name__ == "__main__":12 typer.run(main)modified:docs_src/arguments/help/tutorial005.py+1 added-1 removed
4 unmodified lines5 name: str = typer.Argument(6 "Wade Wilson", help="Who to greet", show_default="Deadpoolio the amazing's name"7 )8 ):9- typer.echo(f"Hello {name}")9+ print(f"Hello {name}")10 11 12 if __name__ == "__main__":13 typer.run(main)modified:docs_src/arguments/help/tutorial006.py+1 added-1 removed
1 import typer2 3 4 def main(name: str = typer.Argument("World", metavar="✨username✨")):5- typer.echo(f"Hello {name}")5+ print(f"Hello {name}")6 7 8 if __name__ == "__main__":9 typer.run(main)modified:docs_src/arguments/help/tutorial007.py+10 added-2 removed
1 import typer2 3 4-def main(name: str = typer.Argument("World", hidden=True)):4+def main(5+ name: str = typer.Argument(..., help="Who to greet"),6+ lastname: str = typer.Argument(7+ "", help="The last name", rich_help_panel="Secondary Arguments"8+ ),9+ age: str = typer.Argument(10+ "", help="The user's age", rich_help_panel="Secondary Arguments"11+ ),12+):13 """14 Say hi to NAME very gently, like Dirk.15 """8- typer.echo(f"Hello {name}")16+ print(f"Hello {name}")17 18 19 if __name__ == "__main__":20 typer.run(main)added:docs_src/arguments/help/tutorial008.py+12 added
1+import typer2+3+4+def main(name: str = typer.Argument("World", hidden=True)):5+ """6+ Say hi to NAME very gently, like Dirk.7+ """8+ print(f"Hello {name}")9+10+11+if __name__ == "__main__":12+ typer.run(main)modified:docs_src/arguments/optional/tutorial001.py+1 added-1 removed
1 import typer2 3 4 def main(name: str = typer.Argument(...)):5- typer.echo(f"Hello {name}")5+ print(f"Hello {name}")6 7 8 if __name__ == "__main__":9 typer.run(main)modified:docs_src/arguments/optional/tutorial002.py+2 added-2 removed
3 unmodified lines4 5 6 def main(name: Optional[str] = typer.Argument(None)):7 if name is None:8- typer.echo("Hello World!")8+ print("Hello World!")9 else:10- typer.echo(f"Hello {name}")10+ print(f"Hello {name}")11 12 13 if __name__ == "__main__":14 typer.run(main)modified:docs_src/commands/arguments/tutorial001.py+2 added-2 removed
3 unmodified lines4 5 6 @app.command()7 def create(username: str):8- typer.echo(f"Creating user: {username}")8+ print(f"Creating user: {username}")9 10 11 @app.command()12 def delete(username: str):13- typer.echo(f"Deleting user: {username}")13+ print(f"Deleting user: {username}")14 15 16 if __name__ == "__main__":17 app()modified:docs_src/commands/callback/tutorial001.py+7 added-7 removed
5 unmodified lines6 7 @app.command()8 def create(username: str):9 if state["verbose"]:10- typer.echo("About to create a user")11- typer.echo(f"Creating user: {username}")10+ print("About to create a user")11+ print(f"Creating user: {username}")12 if state["verbose"]:13- typer.echo("Just created a user")13+ print("Just created a user")14 15 16 @app.command()17 def delete(username: str):18 if state["verbose"]:19- typer.echo("About to delete a user")20- typer.echo(f"Deleting user: {username}")19+ print("About to delete a user")20+ print(f"Deleting user: {username}")21 if state["verbose"]:22- typer.echo("Just deleted a user")22+ print("Just deleted a user")23 24 25 @app.callback()26 def main(verbose: bool = False):27 """28 Manage users in the awesome CLI app.29 """30 if verbose:31- typer.echo("Will write verbose output")31+ print("Will write verbose output")32 state["verbose"] = True33 34 35 if __name__ == "__main__":1 unmodified linemodified:docs_src/commands/callback/tutorial002.py+2 added-2 removed
1 import typer2 3 4 def callback():5- typer.echo("Running a command")5+ print("Running a command")6 7 8 app = typer.Typer(callback=callback)9 10 11 @app.command()12 def create(name: str):13- typer.echo(f"Creating user: {name}")13+ print(f"Creating user: {name}")14 15 16 if __name__ == "__main__":17 app()modified:docs_src/commands/callback/tutorial003.py+3 added-3 removed
1 import typer2 3 4 def callback():5- typer.echo("Running a command")5+ print("Running a command")6 7 8 app = typer.Typer(callback=callback)9 10 11 @app.callback()12 def new_callback():13- typer.echo("Override callback, running a command")13+ print("Override callback, running a command")14 15 16 @app.command()17 def create(name: str):18- typer.echo(f"Creating user: {name}")18+ print(f"Creating user: {name}")19 20 21 if __name__ == "__main__":22 app()modified:docs_src/commands/callback/tutorial004.py+1 added-1 removed
14 unmodified lines15 16 17 @app.command()18 def create(name: str):19- typer.echo(f"Creating user: {name}")19+ print(f"Creating user: {name}")20 21 22 if __name__ == "__main__":23 app()modified:docs_src/commands/context/tutorial001.py+3 added-3 removed
3 unmodified lines4 5 6 @app.command()7 def create(username: str):8- typer.echo(f"Creating user: {username}")8+ print(f"Creating user: {username}")9 10 11 @app.command()12 def delete(username: str):13- typer.echo(f"Deleting user: {username}")13+ print(f"Deleting user: {username}")14 15 16 @app.callback()17 def main(ctx: typer.Context):18 """19 Manage users in the awesome CLI app.20 """21- typer.echo(f"About to execute command: {ctx.invoked_subcommand}")21+ print(f"About to execute command: {ctx.invoked_subcommand}")22 23 24 if __name__ == "__main__":25 app()modified:docs_src/commands/context/tutorial002.py+3 added-3 removed
3 unmodified lines4 5 6 @app.command()7 def create(username: str):8- typer.echo(f"Creating user: {username}")8+ print(f"Creating user: {username}")9 10 11 @app.command()12 def delete(username: str):13- typer.echo(f"Deleting user: {username}")13+ print(f"Deleting user: {username}")14 15 16 @app.callback(invoke_without_command=True)17 def main():18 """19 Manage users in the awesome CLI app.20 """21- typer.echo("Initializing database")21+ print("Initializing database")22 23 24 if __name__ == "__main__":25 app()modified:docs_src/commands/context/tutorial003.py+3 added-3 removed
3 unmodified lines4 5 6 @app.command()7 def create(username: str):8- typer.echo(f"Creating user: {username}")8+ print(f"Creating user: {username}")9 10 11 @app.command()12 def delete(username: str):13- typer.echo(f"Deleting user: {username}")13+ print(f"Deleting user: {username}")14 15 16 @app.callback(invoke_without_command=True)17 def main(ctx: typer.Context):18 """19 Manage users in the awesome CLI app.20 """21 if ctx.invoked_subcommand is None:22- typer.echo("Initializing database")22+ print("Initializing database")23 24 25 if __name__ == "__main__":26 app()modified:docs_src/commands/context/tutorial004.py+1 added-1 removed
6 unmodified lines7 context_settings={"allow_extra_args": True, "ignore_unknown_options": True}8 )9 def main(ctx: typer.Context):10 for extra_arg in ctx.args:11- typer.echo(f"Got extra arg: {extra_arg}")11+ print(f"Got extra arg: {extra_arg}")12 13 14 if __name__ == "__main__":15 app()modified:docs_src/commands/help/tutorial001.py+6 added-6 removed
6 unmodified lines7 def create(username: str):8 """9 Create a new user with USERNAME.10 """11- typer.echo(f"Creating user: {username}")11+ print(f"Creating user: {username}")12 13 14 @app.command()15 def delete(9 unmodified lines25 26 If --force is not used, will ask for confirmation.27 """28 if force:29- typer.echo(f"Deleting user: {username}")29+ print(f"Deleting user: {username}")30 else:31- typer.echo("Operation cancelled")31+ print("Operation cancelled")32 33 34 @app.command()35 def delete_all(8 unmodified lines44 45 If --force is not used, will ask for confirmation.46 """47 if force:48- typer.echo("Deleting all users")48+ print("Deleting all users")49 else:50- typer.echo("Operation cancelled")50+ print("Operation cancelled")51 52 53 @app.command()54 def init():55 """56 Initialize the users database.57 """58- typer.echo("Initializing user database")58+ print("Initializing user database")59 60 61 if __name__ == "__main__":62 app()modified:docs_src/commands/help/tutorial002.py+2 added-2 removed
6 unmodified lines7 def create(username: str):8 """9 Some internal utility function to create.10 """11- typer.echo(f"Creating user: {username}")11+ print(f"Creating user: {username}")12 13 14 @app.command(help="Delete a user with USERNAME.")15 def delete(username: str):16 """17 Some internal utility function to delete.18 """19- typer.echo(f"Deleting user: {username}")19+ print(f"Deleting user: {username}")20 21 22 if __name__ == "__main__":23 app()added:docs_src/commands/help/tutorial003.py+25 added
1+import typer2+3+app = typer.Typer()4+5+6+@app.command()7+def create(username: str):8+ """9+ Create a user.10+ """11+ print(f"Creating user: {username}")12+13+14+@app.command(deprecated=True)15+def delete(username: str):16+ """17+ Delete a user.18+19+ This is deprecated and will stop being supported soon.20+ """21+ print(f"Deleting user: {username}")22+23+24+if __name__ == "__main__":25+ app()added:docs_src/commands/help/tutorial004.py+34 added
1+import typer2+3+app = typer.Typer(rich_markup_mode="rich")4+5+6+@app.command()7+def create(8+ username: str = typer.Argument(9+ ..., help="The username to be [green]created[/green]"10+ )11+):12+ """13+ [bold green]Create[/bold green] a new [italic]shinny[/italic] user. :sparkles:14+15+ This requires a [underline]username[/underline].16+ """17+ print(f"Creating user: {username}")18+19+20+@app.command(help="[bold red]Delete[/bold red] a user with [italic]USERNAME[/italic].")21+def delete(22+ username: str = typer.Argument(..., help="The username to be [red]deleted[/red]"),23+ force: bool = typer.Option(24+ False, help="Force the [bold red]deletion[/bold red] :boom:"25+ ),26+):27+ """28+ Some internal utility function to delete.29+ """30+ print(f"Deleting user: {username}")31+32+33+if __name__ == "__main__":34+ app()added:docs_src/commands/help/tutorial005.py+34 added
1+import typer2+3+app = typer.Typer(rich_markup_mode="markdown")4+5+6+@app.command()7+def create(username: str = typer.Argument(..., help="The username to be **created**")):8+ """9+ **Create** a new *shinny* user. :sparkles:10+11+ * Create a username12+13+ * Show that the username is created14+15+ ---16+17+ Learn more at the [Typer docs website](https://typer.tiangolo.com)18+ """19+ print(f"Creating user: {username}")20+21+22+@app.command(help="**Delete** a user with *USERNAME*.")23+def delete(24+ username: str = typer.Argument(..., help="The username to be **deleted**"),25+ force: bool = typer.Option(False, help="Force the **deletion** :boom:"),26+):27+ """28+ Some internal utility function to delete.29+ """30+ print(f"Deleting user: {username}")31+32+33+if __name__ == "__main__":34+ app()added:docs_src/commands/help/tutorial006.py+55 added
1+import typer2+3+app = typer.Typer(rich_markup_mode="rich")4+5+6+@app.command()7+def create(username: str):8+ """9+ [green]Create[/green] a new user. :sparkles:10+ """11+ print(f"Creating user: {username}")12+13+14+@app.command()15+def delete(username: str):16+ """17+ [red]Delete[/red] a user. :fire:18+ """19+ print(f"Deleting user: {username}")20+21+22+@app.command(rich_help_panel="Utils and Configs")23+def config(configuration: str):24+ """25+ [blue]Configure[/blue] the system. :wrench:26+ """27+ print(f"Configuring the system with: {configuration}")28+29+30+@app.command(rich_help_panel="Utils and Configs")31+def sync():32+ """33+ [blue]Synchronize[/blue] the system or something fancy like that. :recycle:34+ """35+ print("Syncing the system")36+37+38+@app.command(rich_help_panel="Help and Others")39+def help():40+ """41+ Get [yellow]help[/yellow] with the system. :question:42+ """43+ print("Opening help portal...")44+45+46+@app.command(rich_help_panel="Help and Others")47+def report():48+ """49+ [yellow]Report[/yellow] an issue. :bug:50+ """51+ print("Please open a new issue online, not a direct message")52+53+54+if __name__ == "__main__":55+ app()added:docs_src/commands/help/tutorial007.py+39 added
1+from typing import Union2+3+import typer4+5+app = typer.Typer(rich_markup_mode="rich")6+7+8+@app.command()9+def create(10+ username: str = typer.Argument(..., help="The username to create"),11+ lastname: str = typer.Argument(12+ "", help="The last name of the new user", rich_help_panel="Secondary Arguments"13+ ),14+ force: bool = typer.Option(False, help="Force the creation of the user"),15+ age: Union[int, None] = typer.Option(16+ None, help="The age of the new user", rich_help_panel="Additional Data"17+ ),18+ favorite_color: Union[str, None] = typer.Option(19+ None,20+ help="The favorite color of the new user",21+ rich_help_panel="Additional Data",22+ ),23+):24+ """25+ [green]Create[/green] a new user. :sparkles:26+ """27+ print(f"Creating user: {username}")28+29+30+@app.command(rich_help_panel="Utils and Configs")31+def config(configuration: str):32+ """33+ [blue]Configure[/blue] the system. :wrench:34+ """35+ print(f"Configuring the system with: {configuration}")36+37+38+if __name__ == "__main__":39+ app()added:docs_src/commands/help/tutorial008.py+15 added
1+import typer2+3+app = typer.Typer(rich_markup_mode="rich")4+5+6+@app.command(epilog="Made with :heart: in [blue]Venus[/blue]")7+def create(username: str):8+ """9+ [green]Create[/green] a new user. :sparkles:10+ """11+ print(f"Creating user: {username}")12+13+14+if __name__ == "__main__":15+ app()modified:docs_src/commands/index/tutorial001.py+1 added-1 removed
3 unmodified lines4 5 6 @app.command()7 def main(name: str):8- typer.echo(f"Hello {name}")8+ print(f"Hello {name}")9 10 11 if __name__ == "__main__":12 app()modified:docs_src/commands/index/tutorial002.py+2 added-2 removed
3 unmodified lines4 5 6 @app.command()7 def create():8- typer.echo("Creating user: Hiro Hamada")8+ print("Creating user: Hiro Hamada")9 10 11 @app.command()12 def delete():13- typer.echo("Deleting user: Hiro Hamada")13+ print("Deleting user: Hiro Hamada")14 15 16 if __name__ == "__main__":17 app()modified:docs_src/commands/name/tutorial001.py+2 added-2 removed
3 unmodified lines4 5 6 @app.command("create")7 def cli_create_user(username: str):8- typer.echo(f"Creating user: {username}")8+ print(f"Creating user: {username}")9 10 11 @app.command("delete")12 def cli_delete_user(username: str):13- typer.echo(f"Deleting user: {username}")13+ print(f"Deleting user: {username}")14 15 16 if __name__ == "__main__":17 app()modified:docs_src/commands/one_or_multiple/tutorial001.py+1 added-1 removed
3 unmodified lines4 5 6 @app.command()7 def create():8- typer.echo("Creating user: Hiro Hamada")8+ print("Creating user: Hiro Hamada")9 10 11 @app.callback()12 def callback():5 unmodified linesmodified:docs_src/commands/one_or_multiple/tutorial002.py+1 added-1 removed
3 unmodified lines4 5 6 @app.command()7 def create():8- typer.echo("Creating user: Hiro Hamada")8+ print("Creating user: Hiro Hamada")9 10 11 @app.callback()12 def callback():9 unmodified linesmodified:docs_src/commands/options/tutorial001.py+6 added-6 removed
3 unmodified lines4 5 6 @app.command()7 def create(username: str):8- typer.echo(f"Creating user: {username}")8+ print(f"Creating user: {username}")9 10 11 @app.command()12 def delete(13 username: str,14 force: bool = typer.Option(..., prompt="Are you sure you want to delete the user?"),15 ):16 if force:17- typer.echo(f"Deleting user: {username}")17+ print(f"Deleting user: {username}")18 else:19- typer.echo("Operation cancelled")19+ print("Operation cancelled")20 21 22 @app.command()23 def delete_all(24 force: bool = typer.Option(..., prompt="Are you sure you want to delete ALL users?")25 ):26 if force:27- typer.echo("Deleting all users")27+ print("Deleting all users")28 else:29- typer.echo("Operation cancelled")29+ print("Operation cancelled")30 31 32 @app.command()33 def init():34- typer.echo("Initializing user database")34+ print("Initializing user database")35 36 37 if __name__ == "__main__":38 app()modified:docs_src/first_steps/tutorial001.py+1 added-1 removed
1 import typer2 3 4 def main():5- typer.echo("Hello World")5+ print("Hello World")6 7 8 if __name__ == "__main__":9 typer.run(main)modified:docs_src/first_steps/tutorial002.py+1 added-1 removed
1 import typer2 3 4 def main(name: str):5- typer.echo(f"Hello {name}")5+ print(f"Hello {name}")6 7 8 if __name__ == "__main__":9 typer.run(main)modified:docs_src/first_steps/tutorial003.py+1 added-1 removed
1 import typer2 3 4 def main(name: str, lastname: str):5- typer.echo(f"Hello {name} {lastname}")5+ print(f"Hello {name} {lastname}")6 7 8 if __name__ == "__main__":9 typer.run(main)modified:docs_src/first_steps/tutorial004.py+2 added-2 removed
1 unmodified line2 3 4 def main(name: str, lastname: str, formal: bool = False):5 if formal:6- typer.echo(f"Good day Ms. {name} {lastname}.")6+ print(f"Good day Ms. {name} {lastname}.")7 else:8- typer.echo(f"Hello {name} {lastname}")8+ print(f"Hello {name} {lastname}")9 10 11 if __name__ == "__main__":12 typer.run(main)modified:docs_src/first_steps/tutorial005.py+2 added-2 removed
1 unmodified line2 3 4 def main(name: str, lastname: str = "", formal: bool = False):5 if formal:6- typer.echo(f"Good day Ms. {name} {lastname}.")6+ print(f"Good day Ms. {name} {lastname}.")7 else:8- typer.echo(f"Hello {name} {lastname}")8+ print(f"Hello {name} {lastname}")9 10 11 if __name__ == "__main__":12 typer.run(main)modified:docs_src/first_steps/tutorial006.py+2 added-2 removed
6 unmodified lines7 8 If --formal is used, say hi very formally.9 """10 if formal:11- typer.echo(f"Good day Ms. {name} {lastname}.")11+ print(f"Good day Ms. {name} {lastname}.")12 else:13- typer.echo(f"Hello {name} {lastname}")13+ print(f"Hello {name} {lastname}")14 15 16 if __name__ == "__main__":17 typer.run(main)modified:docs_src/launch/tutorial001.py+1 added-1 removed
1 import typer2 3 4 def main():5- typer.echo("Opening Typer's docs")5+ print("Opening Typer's docs")6 typer.launch("https://typer.tiangolo.com")7 8 9 if __name__ == "__main__":1 unmodified linemodified:docs_src/launch/tutorial002.py+1 added-1 removed
11 unmodified lines12 config_path: Path = Path(app_dir) / "config.json"13 if not config_path.is_file():14 config_path.write_text('{"version": "1.0.0"}')15 config_file_str = str(config_path)16- typer.echo("Opening config directory")16+ print("Opening config directory")17 typer.launch(config_file_str, locate=True)18 19 20 if __name__ == "__main__":1 unmodified linemodified:docs_src/multiple_values/arguments_with_multiple_values/tutorial001.py+2 added-2 removed
5 unmodified lines6 7 def main(files: List[Path], celebration: str):8 for path in files:9 if path.is_file():10- typer.echo(f"This file exists: {path.name}")11- typer.echo(celebration)10+ print(f"This file exists: {path.name}")11+ print(celebration)12 13 14 if __name__ == "__main__":15 typer.run(main)modified:docs_src/multiple_values/arguments_with_multiple_values/tutorial002.py+1 added-1 removed
7 unmodified lines8 ("Harry", "Hermione", "Ron"), help="Select 3 characters to play with"9 )10 ):11 for name in names:12- typer.echo(f"Hello {name}")12+ print(f"Hello {name}")13 14 15 if __name__ == "__main__":16 typer.run(main)modified:docs_src/multiple_values/multiple_options/tutorial001.py+2 added-2 removed
3 unmodified lines4 5 6 def main(user: Optional[List[str]] = typer.Option(None)):7 if not user:8- typer.echo("No provided users")8+ print("No provided users")9 raise typer.Abort()10 for u in user:11- typer.echo(f"Processing user: {u}")11+ print(f"Processing user: {u}")12 13 14 if __name__ == "__main__":15 typer.run(main)modified:docs_src/multiple_values/multiple_options/tutorial002.py+1 added-1 removed
2 unmodified lines3 import typer4 5 6 def main(number: List[float] = typer.Option([])):7- typer.echo(f"The sum is {sum(number)}")7+ print(f"The sum is {sum(number)}")8 9 10 if __name__ == "__main__":11 typer.run(main)modified:docs_src/multiple_values/options_with_multiple_values/tutorial001.py+3 added-3 removed
4 unmodified lines5 6 def main(user: Tuple[str, int, bool] = typer.Option((None, None, None))):7 username, coins, is_wizard = user8 if not username:9- typer.echo("No user provided")9+ print("No user provided")10 raise typer.Abort()11- typer.echo(f"The username {username} has {coins} coins")11+ print(f"The username {username} has {coins} coins")12 if is_wizard:13- typer.echo("And this user is a wizard!")13+ print("And this user is a wizard!")14 15 16 if __name__ == "__main__":17 typer.run(main)modified:docs_src/options/autocompletion/tutorial001.py+1 added-1 removed
1 import typer2 3 4 def main(name: str = typer.Option("World", help="The name to say hi to.")):5- typer.echo(f"Hello {name}")5+ print(f"Hello {name}")6 7 8 if __name__ == "__main__":9 typer.run(main)modified:docs_src/options/autocompletion/tutorial002.py+1 added-1 removed
8 unmodified lines9 name: str = typer.Option(10 "World", help="The name to say hi to.", autocompletion=complete_name11 )12 ):13- typer.echo(f"Hello {name}")13+ print(f"Hello {name}")14 15 16 if __name__ == "__main__":17 typer.run(main)modified:docs_src/options/autocompletion/tutorial003.py+1 added-1 removed
14 unmodified lines15 name: str = typer.Option(16 "World", help="The name to say hi to.", autocompletion=complete_name17 )18 ):19- typer.echo(f"Hello {name}")19+ print(f"Hello {name}")20 21 22 if __name__ == "__main__":23 typer.run(main)modified:docs_src/options/autocompletion/tutorial004.py+1 added-1 removed
19 unmodified lines20 name: str = typer.Option(21 "World", help="The name to say hi to.", autocompletion=complete_name22 )23 ):24- typer.echo(f"Hello {name}")24+ print(f"Hello {name}")25 26 27 if __name__ == "__main__":28 typer.run(main)modified:docs_src/options/autocompletion/tutorial005.py+1 added-1 removed
16 unmodified lines17 name: str = typer.Option(18 "World", help="The name to say hi to.", autocompletion=complete_name19 )20 ):21- typer.echo(f"Hello {name}")21+ print(f"Hello {name}")22 23 24 if __name__ == "__main__":25 typer.run(main)modified:docs_src/options/autocompletion/tutorial006.py+1 added-1 removed
3 unmodified lines4 5 6 def main(name: List[str] = typer.Option(["World"], help="The name to say hi to.")):7 for each_name in name:8- typer.echo(f"Hello {each_name}")8+ print(f"Hello {each_name}")9 10 11 if __name__ == "__main__":12 typer.run(main)modified:docs_src/options/autocompletion/tutorial007.py+1 added-1 removed
20 unmodified lines21 ["World"], help="The name to say hi to.", autocompletion=complete_name22 )23 ):24 for n in name:25- typer.echo(f"Hello {n}")25+ print(f"Hello {n}")26 27 28 if __name__ == "__main__":29 typer.run(main)modified:docs_src/options/autocompletion/tutorial008.py+5 added-2 removed
1 from typing import List2 3 import typer4+from rich.console import Console5 6 valid_completion_items = [7 ("Camila", "The reader of books."),8 ("Carlos", "The writer of scripts."),9 ("Sebastian", "The type hints guy."),10 ]11 12+err_console = Console(stderr=True)13 14+15 def complete_name(args: List[str], incomplete: str):13- typer.echo(f"{args}", err=True)16+ err_console.print(f"{args}")17 for name, help_text in valid_completion_items:18 if name.startswith(incomplete):19 yield (name, help_text)20 3 unmodified lines24 ["World"], help="The name to say hi to.", autocompletion=complete_name25 )26 ):27 for n in name:25- typer.echo(f"Hello {n}")28+ print(f"Hello {n}")29 30 31 if __name__ == "__main__":32 typer.run(main)modified:docs_src/options/autocompletion/tutorial009.py+5 added-2 removed
1 from typing import List2 3 import typer4+from rich.console import Console5 6 valid_completion_items = [7 ("Camila", "The reader of books."),8 ("Carlos", "The writer of scripts."),9 ("Sebastian", "The type hints guy."),10 ]11 12+err_console = Console(stderr=True)13 14+15 def complete_name(ctx: typer.Context, args: List[str], incomplete: str):13- typer.echo(f"{args}", err=True)16+ err_console.print(f"{args}")17 names = ctx.params.get("name") or []18 for name, help_text in valid_completion_items:19 if name.startswith(incomplete) and name not in names:20 yield (name, help_text)4 unmodified lines25 ["World"], help="The name to say hi to.", autocompletion=complete_name26 )27 ):28 for n in name:26- typer.echo(f"Hello {n}")29+ print(f"Hello {n}")30 31 32 if __name__ == "__main__":33 typer.run(main)modified:docs_src/options/callback/tutorial001.py+1 added-1 removed
6 unmodified lines7 return value8 9 10 def main(name: str = typer.Option(..., callback=name_callback)):11- typer.echo(f"Hello {name}")11+ print(f"Hello {name}")12 13 14 if __name__ == "__main__":15 typer.run(main)modified:docs_src/options/callback/tutorial002.py+2 added-2 removed
1 import typer2 3 4 def name_callback(value: str):5- typer.echo("Validating name")5+ print("Validating name")6 if value != "Camila":7 raise typer.BadParameter("Only Camila is allowed")8 return value9 10 11 def main(name: str = typer.Option(..., callback=name_callback)):12- typer.echo(f"Hello {name}")12+ print(f"Hello {name}")13 14 15 if __name__ == "__main__":16 typer.run(main)modified:docs_src/options/callback/tutorial003.py+2 added-2 removed
2 unmodified lines3 4 def name_callback(ctx: typer.Context, value: str):5 if ctx.resilient_parsing:6 return7- typer.echo("Validating name")7+ print("Validating name")8 if value != "Camila":9 raise typer.BadParameter("Only Camila is allowed")10 return value11 12 13 def main(name: str = typer.Option(..., callback=name_callback)):14- typer.echo(f"Hello {name}")14+ print(f"Hello {name}")15 16 17 if __name__ == "__main__":18 typer.run(main)modified:docs_src/options/callback/tutorial004.py+2 added-2 removed
2 unmodified lines3 4 def name_callback(ctx: typer.Context, param: typer.CallbackParam, value: str):5 if ctx.resilient_parsing:6 return7- typer.echo(f"Validating param: {param.name}")7+ print(f"Validating param: {param.name}")8 if value != "Camila":9 raise typer.BadParameter("Only Camila is allowed")10 return value11 12 13 def main(name: str = typer.Option(..., callback=name_callback)):14- typer.echo(f"Hello {name}")14+ print(f"Hello {name}")15 16 17 if __name__ == "__main__":18 typer.run(main)modified:docs_src/options/help/tutorial001.py+2 added-2 removed
10 unmodified lines11 12 If --formal is used, say hi very formally.13 """14 if formal:15- typer.echo(f"Good day Ms. {name} {lastname}.")15+ print(f"Good day Ms. {name} {lastname}.")16 else:17- typer.echo(f"Hello {name} {lastname}")17+ print(f"Hello {name} {lastname}")18 19 20 if __name__ == "__main__":21 typer.run(main)modified:docs_src/options/help/tutorial002.py+19 added-2 removed
1 import typer2 3 4-def main(fullname: str = typer.Option("Wade Wilson", show_default=False)):5- typer.echo(f"Hello {fullname}")4+def main(5+ name: str,6+ lastname: str = typer.Option("", help="Last name of person to greet."),7+ formal: bool = typer.Option(8+ False, help="Say hi formally.", rich_help_panel="Customization and Utils"9+ ),10+ debug: bool = typer.Option(11+ False, help="Enable debugging.", rich_help_panel="Customization and Utils"12+ ),13+):14+ """15+ Say hi to NAME, optionally with a --lastname.16 17+ If --formal is used, say hi very formally.18+ """19+ if formal:20+ print(f"Good day Ms. {name} {lastname}.")21+ else:22+ print(f"Hello {name} {lastname}")23 24+25 if __name__ == "__main__":26 typer.run(main)added:docs_src/options/help/tutorial003.py+9 added
1+import typer2+3+4+def main(fullname: str = typer.Option("Wade Wilson", show_default=False)):5+ print(f"Hello {fullname}")6+7+8+if __name__ == "__main__":9+ typer.run(main)modified:docs_src/options/name/tutorial001.py+1 added-1 removed
1 import typer2 3 4 def main(user_name: str = typer.Option(..., "--name")):5- typer.echo(f"Hello {user_name}")5+ print(f"Hello {user_name}")6 7 8 if __name__ == "__main__":9 typer.run(main)modified:docs_src/options/name/tutorial002.py+1 added-1 removed
1 import typer2 3 4 def main(user_name: str = typer.Option(..., "--name", "-n")):5- typer.echo(f"Hello {user_name}")5+ print(f"Hello {user_name}")6 7 8 if __name__ == "__main__":9 typer.run(main)modified:docs_src/options/name/tutorial003.py+1 added-1 removed
1 import typer2 3 4 def main(user_name: str = typer.Option(..., "-n")):5- typer.echo(f"Hello {user_name}")5+ print(f"Hello {user_name}")6 7 8 if __name__ == "__main__":9 typer.run(main)modified:docs_src/options/name/tutorial004.py+1 added-1 removed
1 import typer2 3 4 def main(user_name: str = typer.Option(..., "--user-name", "-n")):5- typer.echo(f"Hello {user_name}")5+ print(f"Hello {user_name}")6 7 8 if __name__ == "__main__":9 typer.run(main)modified:docs_src/options/name/tutorial005.py+2 added-2 removed
4 unmodified lines5 name: str = typer.Option(..., "--name", "-n"),6 formal: bool = typer.Option(False, "--formal", "-f"),7 ):8 if formal:9- typer.echo(f"Good day Ms. {name}.")9+ print(f"Good day Ms. {name}.")10 else:11- typer.echo(f"Hello {name}")11+ print(f"Hello {name}")12 13 14 if __name__ == "__main__":15 typer.run(main)modified:docs_src/options/password/tutorial001.py+1 added-1 removed
2 unmodified lines3 4 def main(5 name: str, email: str = typer.Option(..., prompt=True, confirmation_prompt=True)6 ):7- typer.echo(f"Hello {name}, your email is {email}")7+ print(f"Hello {name}, your email is {email}")8 9 10 if __name__ == "__main__":11 typer.run(main)modified:docs_src/options/password/tutorial002.py+2 added-2 removed
5 unmodified lines6 password: str = typer.Option(7 ..., prompt=True, confirmation_prompt=True, hide_input=True8 ),9 ):10- typer.echo(f"Hello {name}. Doing something very secure with password.")11- typer.echo(f"...just kidding, here it is, very insecure: {password}")10+ print(f"Hello {name}. Doing something very secure with password.")11+ print(f"...just kidding, here it is, very insecure: {password}")12 13 14 if __name__ == "__main__":15 typer.run(main)modified:docs_src/options/prompt/tutorial001.py+1 added-1 removed
1 import typer2 3 4 def main(name: str, lastname: str = typer.Option(..., prompt=True)):5- typer.echo(f"Hello {name} {lastname}")5+ print(f"Hello {name} {lastname}")6 7 8 if __name__ == "__main__":9 typer.run(main)modified:docs_src/options/prompt/tutorial002.py+1 added-1 removed
2 unmodified lines3 4 def main(5 name: str, lastname: str = typer.Option(..., prompt="Please tell me your last name")6 ):7- typer.echo(f"Hello {name} {lastname}")7+ print(f"Hello {name} {lastname}")8 9 10 if __name__ == "__main__":11 typer.run(main)modified:docs_src/options/prompt/tutorial003.py+1 added-1 removed
1 import typer2 3 4 def main(project_name: str = typer.Option(..., prompt=True, confirmation_prompt=True)):5- typer.echo(f"Deleting project {project_name}")5+ print(f"Deleting project {project_name}")6 7 8 if __name__ == "__main__":9 typer.run(main)modified:docs_src/options/required/tutorial001.py+1 added-1 removed
1 import typer2 3 4 def main(name: str, lastname: str = typer.Option(...)):5- typer.echo(f"Hello {name} {lastname}")5+ print(f"Hello {name} {lastname}")6 7 8 if __name__ == "__main__":9 typer.run(main)modified:docs_src/options/version/tutorial001.py+2 added-2 removed
5 unmodified lines6 7 8 def version_callback(value: bool):9 if value:10- typer.echo(f"Awesome CLI Version: {__version__}")10+ print(f"Awesome CLI Version: {__version__}")11 raise typer.Exit()12 13 14 def main(1 unmodified line16 version: Optional[bool] = typer.Option(17 None, "--version", callback=version_callback18 ),19 ):20- typer.echo(f"Hello {name}")20+ print(f"Hello {name}")21 22 23 if __name__ == "__main__":24 typer.run(main)modified:docs_src/options/version/tutorial002.py+2 added-2 removed
5 unmodified lines6 7 8 def version_callback(value: bool):9 if value:10- typer.echo(f"Awesome CLI Version: {__version__}")10+ print(f"Awesome CLI Version: {__version__}")11 raise typer.Exit()12 13 14 def name_callback(name: str):6 unmodified lines21 version: Optional[bool] = typer.Option(22 None, "--version", callback=version_callback23 ),24 ):25- typer.echo(f"Hello {name}")25+ print(f"Hello {name}")26 27 28 if __name__ == "__main__":29 typer.run(main)modified:docs_src/options/version/tutorial003.py+2 added-2 removed
5 unmodified lines6 7 8 def version_callback(value: bool):9 if value:10- typer.echo(f"Awesome CLI Version: {__version__}")10+ print(f"Awesome CLI Version: {__version__}")11 raise typer.Exit()12 13 14 def name_callback(name: str):7 unmodified lines22 version: Optional[bool] = typer.Option(23 None, "--version", callback=version_callback, is_eager=True24 ),25 ):26- typer.echo(f"Hello {name}")26+ print(f"Hello {name}")27 28 29 if __name__ == "__main__":30 typer.run(main)modified:docs_src/parameter_types/bool/tutorial001.py+2 added-2 removed
1 unmodified line2 3 4 def main(force: bool = typer.Option(False, "--force")):5 if force:6- typer.echo("Forcing operation")6+ print("Forcing operation")7 else:8- typer.echo("Not forcing")8+ print("Not forcing")9 10 11 if __name__ == "__main__":12 typer.run(main)modified:docs_src/parameter_types/bool/tutorial002.py+3 added-3 removed
3 unmodified lines4 5 6 def main(accept: Optional[bool] = typer.Option(None, "--accept/--reject")):7 if accept is None:8- typer.echo("I don't know what you want yet")8+ print("I don't know what you want yet")9 elif accept:10- typer.echo("Accepting!")10+ print("Accepting!")11 else:12- typer.echo("Rejecting!")12+ print("Rejecting!")13 14 15 if __name__ == "__main__":16 typer.run(main)modified:docs_src/parameter_types/bool/tutorial003.py+2 added-2 removed
1 unmodified line2 3 4 def main(force: bool = typer.Option(False, "--force/--no-force", "-f/-F")):5 if force:6- typer.echo("Forcing operation")6+ print("Forcing operation")7 else:8- typer.echo("Not forcing")8+ print("Not forcing")9 10 11 if __name__ == "__main__":12 typer.run(main)modified:docs_src/parameter_types/bool/tutorial004.py+2 added-2 removed
1 unmodified line2 3 4 def main(in_prod: bool = typer.Option(True, " /--demo", " /-d")):5 if in_prod:6- typer.echo("Running in production")6+ print("Running in production")7 else:8- typer.echo("Running demo")8+ print("Running demo")9 10 11 if __name__ == "__main__":12 typer.run(main)modified:docs_src/parameter_types/datetime/tutorial001.py+2 added-2 removed
2 unmodified lines3 import typer4 5 6 def main(birth: datetime):7- typer.echo(f"Interesting day to be born: {birth}")8- typer.echo(f"Birth hour: {birth.hour}")7+ print(f"Interesting day to be born: {birth}")8+ print(f"Birth hour: {birth.hour}")9 10 11 if __name__ == "__main__":12 typer.run(main)modified:docs_src/parameter_types/datetime/tutorial002.py+1 added-1 removed
6 unmodified lines7 launch_date: datetime = typer.Argument(8 ..., formats=["%Y-%m-%d", "%Y-%m-%dT%H:%M:%S", "%Y-%m-%d %H:%M:%S", "%m/%d/%Y"]9 )10 ):11- typer.echo(f"Launch will be at: {launch_date}")11+ print(f"Launch will be at: {launch_date}")12 13 14 if __name__ == "__main__":15 typer.run(main)modified:docs_src/parameter_types/enum/tutorial001.py+1 added-1 removed
8 unmodified lines9 lstm = "lstm"10 11 12 def main(network: NeuralNetwork = NeuralNetwork.simple):13- typer.echo(f"Training neural network of type: {network.value}")13+ print(f"Training neural network of type: {network.value}")14 15 16 if __name__ == "__main__":17 typer.run(main)modified:docs_src/parameter_types/enum/tutorial002.py+1 added-1 removed
10 unmodified lines11 12 def main(13 network: NeuralNetwork = typer.Option(NeuralNetwork.simple, case_sensitive=False)14 ):15- typer.echo(f"Training neural network of type: {network.value}")15+ print(f"Training neural network of type: {network.value}")16 17 18 if __name__ == "__main__":19 typer.run(main)modified:docs_src/parameter_types/file/tutorial001.py+1 added-1 removed
1 unmodified line2 3 4 def main(config: typer.FileText = typer.Option(...)):5 for line in config:6- typer.echo(f"Config line: {line}")6+ print(f"Config line: {line}")7 8 9 if __name__ == "__main__":10 typer.run(main)modified:docs_src/parameter_types/file/tutorial002.py+1 added-1 removed
1 unmodified line2 3 4 def main(config: typer.FileTextWrite = typer.Option(...)):5 config.write("Some config written by the app")6- typer.echo("Config written")6+ print("Config written")7 8 9 if __name__ == "__main__":10 typer.run(main)modified:docs_src/parameter_types/file/tutorial003.py+1 added-1 removed
4 unmodified lines5 processed_total = 06 for bytes_chunk in file:7 # Process the bytes in bytes_chunk8 processed_total += len(bytes_chunk)9- typer.echo(f"Processed bytes total: {processed_total}")9+ print(f"Processed bytes total: {processed_total}")10 11 12 if __name__ == "__main__":13 typer.run(main)modified:docs_src/parameter_types/file/tutorial004.py+1 added-1 removed
8 unmodified lines9 file.write(first_line_bytes)10 # This is already bytes, it starts with b"11 second_line = b"la cig\xc3\xbce\xc3\xb1a trae al ni\xc3\xb1o"12 file.write(second_line)13- typer.echo("Binary file written")13+ print("Binary file written")14 15 16 if __name__ == "__main__":17 typer.run(main)modified:docs_src/parameter_types/file/tutorial005.py+1 added-1 removed
1 unmodified line2 3 4 def main(config: typer.FileText = typer.Option(..., mode="a")):5 config.write("This is a single line\n")6- typer.echo("Config line written")6+ print("Config line written")7 8 9 if __name__ == "__main__":10 typer.run(main)modified:docs_src/parameter_types/index/tutorial001.py+4 added-4 removed
1 import typer2 3 4 def main(name: str, age: int = 20, height_meters: float = 1.89, female: bool = True):5- typer.echo(f"NAME is {name}, of type: {type(name)}")6- typer.echo(f"--age is {age}, of type: {type(age)}")7- typer.echo(f"--height-meters is {height_meters}, of type: {type(height_meters)}")8- typer.echo(f"--female is {female}, of type: {type(female)}")5+ print(f"NAME is {name}, of type: {type(name)}")6+ print(f"--age is {age}, of type: {type(age)}")7+ print(f"--height-meters is {height_meters}, of type: {type(height_meters)}")8+ print(f"--female is {female}, of type: {type(female)}")9 10 11 if __name__ == "__main__":12 typer.run(main)modified:docs_src/parameter_types/number/tutorial001.py+3 added-3 removed
4 unmodified lines5 id: int = typer.Argument(..., min=0, max=1000),6 age: int = typer.Option(20, min=18),7 score: float = typer.Option(0, max=100),8 ):9- typer.echo(f"ID is {id}")10- typer.echo(f"--age is {age}")11- typer.echo(f"--score is {score}")9+ print(f"ID is {id}")10+ print(f"--age is {age}")11+ print(f"--score is {score}")12 13 14 if __name__ == "__main__":15 typer.run(main)modified:docs_src/parameter_types/number/tutorial002.py+3 added-3 removed
4 unmodified lines5 id: int = typer.Argument(..., min=0, max=1000),6 rank: int = typer.Option(0, max=10, clamp=True),7 score: float = typer.Option(0, min=0, max=100, clamp=True),8 ):9- typer.echo(f"ID is {id}")10- typer.echo(f"--rank is {rank}")11- typer.echo(f"--score is {score}")9+ print(f"ID is {id}")10+ print(f"--rank is {rank}")11+ print(f"--score is {score}")12 13 14 if __name__ == "__main__":15 typer.run(main)modified:docs_src/parameter_types/number/tutorial003.py+1 added-1 removed
1 import typer2 3 4 def main(verbose: int = typer.Option(0, "--verbose", "-v", count=True)):5- typer.echo(f"Verbose level is {verbose}")5+ print(f"Verbose level is {verbose}")6 7 8 if __name__ == "__main__":9 typer.run(main)modified:docs_src/parameter_types/path/tutorial001.py+4 added-4 removed
4 unmodified lines5 6 7 def main(config: Optional[Path] = typer.Option(None)):8 if config is None:9- typer.echo("No config file")9+ print("No config file")10 raise typer.Abort()11 if config.is_file():12 text = config.read_text()13- typer.echo(f"Config file contents: {text}")13+ print(f"Config file contents: {text}")14 elif config.is_dir():15- typer.echo("Config is a directory, will use all its config files")15+ print("Config is a directory, will use all its config files")16 elif not config.exists():17- typer.echo("The config doesn't exist")17+ print("The config doesn't exist")18 19 20 if __name__ == "__main__":21 typer.run(main)modified:docs_src/parameter_types/path/tutorial002.py+1 added-1 removed
13 unmodified lines14 resolve_path=True,15 )16 ):17 text = config.read_text()18- typer.echo(f"Config file contents: {text}")18+ print(f"Config file contents: {text}")19 20 21 if __name__ == "__main__":22 typer.run(main)modified:docs_src/parameter_types/uuid/tutorial001.py+2 added-2 removed
2 unmodified lines3 import typer4 5 6 def main(user_id: UUID):7- typer.echo(f"USER_ID is {user_id}")8- typer.echo(f"UUID version is: {user_id.version}")7+ print(f"USER_ID is {user_id}")8+ print(f"UUID version is: {user_id.version}")9 10 11 if __name__ == "__main__":12 typer.run(main)modified:docs_src/printing/tutorial001.py+12 added-8 removed
1 import typer2+from rich import print3 4+data = {5+ "name": "Rick",6+ "age": 42,7+ "items": [{"name": "Portal Gun"}, {"name": "Plumbus"}],8+ "active": True,9+ "affiliation": None,10+}11 4-def main(good: bool = True):5- message_start = "everything is "6- if good:7- ending = typer.style("good", fg=typer.colors.GREEN, bold=True)8- else:9- ending = typer.style("bad", fg=typer.colors.WHITE, bg=typer.colors.RED)10- message = message_start + ending11- typer.echo(message)12 13+def main():14+ print("Here's the data")15+ print(data)16 17+18 if __name__ == "__main__":19 typer.run(main)modified:docs_src/printing/tutorial002.py+3 added-2 removed
1 import typer2+from rich import print3 4 4-def main(name: str):5- typer.secho(f"Welcome here {name}", fg=typer.colors.MAGENTA)5+def main():6+ print("[bold red]Alert![/bold red] [green]Portal gun[/green] shooting! :boom:")7 8 9 if __name__ == "__main__":10 typer.run(main)modified:docs_src/printing/tutorial003.py+8 added-1 removed
1 import typer2+from rich.console import Console3+from rich.table import Table4 5+console = Console()6 7+8 def main():5- typer.echo(f"Here is something written to standard error", err=True)9+ table = Table("Name", "Item")10+ table.add_row("Rick", "Portal Gun")11+ table.add_row("Morty", "Plumbus")12+ console.print(table)13 14 15 if __name__ == "__main__":16 typer.run(main)added:docs_src/printing/tutorial004.py+12 added
1+import typer2+from rich.console import Console3+4+err_console = Console(stderr=True)5+6+7+def main():8+ err_console.print("Here is something written to standard error")9+10+11+if __name__ == "__main__":12+ typer.run(main)added:docs_src/printing/tutorial005.py+15 added
1+import typer2+3+4+def main(good: bool = True):5+ message_start = "everything is "6+ if good:7+ ending = typer.style("good", fg=typer.colors.GREEN, bold=True)8+ else:9+ ending = typer.style("bad", fg=typer.colors.WHITE, bg=typer.colors.RED)10+ message = message_start + ending11+ typer.echo(message)12+13+14+if __name__ == "__main__":15+ typer.run(main)added:docs_src/printing/tutorial006.py+9 added
1+import typer2+3+4+def main(name: str):5+ typer.secho(f"Welcome here {name}", fg=typer.colors.MAGENTA)6+7+8+if __name__ == "__main__":9+ typer.run(main)modified:docs_src/progressbar/tutorial001.py+1 added-1 removed
8 unmodified lines9 for value in progress:10 # Fake processing time11 time.sleep(0.01)12 total += 113- typer.echo(f"Processed {total} things.")13+ print(f"Processed {total} things.")14 15 16 if __name__ == "__main__":17 typer.run(main)modified:docs_src/progressbar/tutorial002.py+1 added-1 removed
14 unmodified lines15 for value in progress:16 # Fake processing time17 time.sleep(0.01)18 total += 119- typer.echo(f"Processed {total} user IDs.")19+ print(f"Processed {total} user IDs.")20 21 22 if __name__ == "__main__":23 typer.run(main)modified:docs_src/progressbar/tutorial003.py+1 added-1 removed
8 unmodified lines9 for value in progress:10 # Fake processing time11 time.sleep(0.01)12 total += 113- typer.echo(f"Processed {total} things.")13+ print(f"Processed {total} things.")14 15 16 if __name__ == "__main__":17 typer.run(main)modified:docs_src/progressbar/tutorial004.py+1 added-1 removed
8 unmodified lines9 for batch in range(4):10 # Fake processing time11 time.sleep(1)12 progress.update(250)13- typer.echo(f"Processed {total} things in batches.")13+ print(f"Processed {total} things in batches.")14 15 16 if __name__ == "__main__":17 typer.run(main)modified:docs_src/prompt/tutorial001.py+1 added-1 removed
1 unmodified line2 3 4 def main():5 person_name = typer.prompt("What's your name?")6- typer.echo(f"Hello {person_name}")6+ print(f"Hello {person_name}")7 8 9 if __name__ == "__main__":10 typer.run(main)modified:docs_src/prompt/tutorial002.py+2 added-2 removed
2 unmodified lines3 4 def main():5 delete = typer.confirm("Are you sure you want to delete it?")6 if not delete:7- typer.echo("Not deleting")7+ print("Not deleting")8 raise typer.Abort()9- typer.echo("Deleting it!")9+ print("Deleting it!")10 11 12 if __name__ == "__main__":13 typer.run(main)modified:docs_src/prompt/tutorial003.py+1 added-1 removed
1 unmodified line2 3 4 def main():5 delete = typer.confirm("Are you sure you want to delete it?", abort=True)6- typer.echo("Deleting it!")6+ print("Deleting it!")7 8 9 if __name__ == "__main__":10 typer.run(main)modified:docs_src/subcommands/callback_override/tutorial001.py+2 added-2 removed
6 unmodified lines7 8 9 @users_app.callback()10 def users_callback():11- typer.echo("Running a users command")11+ print("Running a users command")12 13 14 @users_app.command()15 def create(name: str):16- typer.echo(f"Creating user: {name}")16+ print(f"Creating user: {name}")17 18 19 if __name__ == "__main__":20 app()modified:docs_src/subcommands/callback_override/tutorial002.py+2 added-2 removed
2 unmodified lines3 app = typer.Typer()4 5 6 def users_callback():7- typer.echo("Running a users command")7+ print("Running a users command")8 9 10 users_app = typer.Typer(callback=users_callback)11 app.add_typer(users_app, name="users")12 13 14 @users_app.command()15 def create(name: str):16- typer.echo(f"Creating user: {name}")16+ print(f"Creating user: {name}")17 18 19 if __name__ == "__main__":20 app()modified:docs_src/subcommands/callback_override/tutorial003.py+3 added-3 removed
2 unmodified lines3 app = typer.Typer()4 5 6 def default_callback():7- typer.echo("Running a users command")7+ print("Running a users command")8 9 10 users_app = typer.Typer(callback=default_callback)11 app.add_typer(users_app, name="users")12 13 14 @users_app.callback()15 def user_callback():16- typer.echo("Callback override, running users command")16+ print("Callback override, running users command")17 18 19 @users_app.command()20 def create(name: str):21- typer.echo(f"Creating user: {name}")21+ print(f"Creating user: {name}")22 23 24 if __name__ == "__main__":25 app()modified:docs_src/subcommands/callback_override/tutorial004.py+4 added-4 removed
2 unmodified lines3 app = typer.Typer()4 5 6 def default_callback():7- typer.echo("Running a users command")7+ print("Running a users command")8 9 10 users_app = typer.Typer(callback=default_callback)11 12 13 def callback_for_add_typer():14- typer.echo("I have the high land! Running users command")14+ print("I have the high land! Running users command")15 16 17 app.add_typer(users_app, name="users", callback=callback_for_add_typer)18 19 20 @users_app.callback()21 def user_callback():22- typer.echo("Callback override, running users command")22+ print("Callback override, running users command")23 24 25 @users_app.command()26 def create(name: str):27- typer.echo(f"Creating user: {name}")27+ print(f"Creating user: {name}")28 29 30 if __name__ == "__main__":31 app()modified:docs_src/subcommands/name_help/tutorial001.py+1 added-1 removed
6 unmodified lines7 8 9 @users_app.command()10 def create(name: str):11- typer.echo(f"Creating user: {name}")11+ print(f"Creating user: {name}")12 13 14 if __name__ == "__main__":15 app()modified:docs_src/subcommands/name_help/tutorial002.py+1 added-1 removed
13 unmodified lines14 15 16 @users_app.command()17 def create(name: str):18- typer.echo(f"Creating user: {name}")18+ print(f"Creating user: {name}")19 20 21 if __name__ == "__main__":22 app()modified:docs_src/subcommands/name_help/tutorial003.py+1 added-1 removed
13 unmodified lines14 15 16 @users_app.command()17 def create(name: str):18- typer.echo(f"Creating user: {name}")18+ print(f"Creating user: {name}")19 20 21 if __name__ == "__main__":22 app()modified:docs_src/subcommands/name_help/tutorial004.py+1 added-1 removed
20 unmodified lines21 22 23 @users_app.command()24 def create(name: str):25- typer.echo(f"Creating user: {name}")25+ print(f"Creating user: {name}")26 27 28 if __name__ == "__main__":29 app()modified:docs_src/subcommands/name_help/tutorial005.py+1 added-1 removed
28 unmodified lines29 30 31 @users_app.command()32 def create(name: str):33- typer.echo(f"Creating user: {name}")33+ print(f"Creating user: {name}")34 35 36 if __name__ == "__main__":37 app()modified:docs_src/subcommands/name_help/tutorial006.py+1 added-1 removed
28 unmodified lines29 30 31 @users_app.command()32 def create(name: str):33- typer.echo(f"Creating user: {name}")33+ print(f"Creating user: {name}")34 35 36 if __name__ == "__main__":37 app()modified:docs_src/subcommands/name_help/tutorial007.py+1 added-1 removed
28 unmodified lines29 30 31 @users_app.command()32 def create(name: str):33- typer.echo(f"Creating user: {name}")33+ print(f"Creating user: {name}")34 35 36 if __name__ == "__main__":37 app()modified:docs_src/subcommands/name_help/tutorial008.py+1 added-1 removed
33 unmodified lines34 35 36 @users_app.command()37 def create(name: str):38- typer.echo(f"Creating user: {name}")38+ print(f"Creating user: {name}")39 40 41 if __name__ == "__main__":42 app()modified:docs_src/subcommands/tutorial001/items.py+3 added-3 removed
3 unmodified lines4 5 6 @app.command()7 def create(item: str):8- typer.echo(f"Creating item: {item}")8+ print(f"Creating item: {item}")9 10 11 @app.command()12 def delete(item: str):13- typer.echo(f"Deleting item: {item}")13+ print(f"Deleting item: {item}")14 15 16 @app.command()17 def sell(item: str):18- typer.echo(f"Selling item: {item}")18+ print(f"Selling item: {item}")19 20 21 if __name__ == "__main__":22 app()modified:docs_src/subcommands/tutorial001/users.py+2 added-2 removed
3 unmodified lines4 5 6 @app.command()7 def create(user_name: str):8- typer.echo(f"Creating user: {user_name}")8+ print(f"Creating user: {user_name}")9 10 11 @app.command()12 def delete(user_name: str):13- typer.echo(f"Deleting user: {user_name}")13+ print(f"Deleting user: {user_name}")14 15 16 if __name__ == "__main__":17 app()modified:docs_src/subcommands/tutorial002/main.py+5 added-5 removed
7 unmodified lines8 9 10 @items_app.command("create")11 def items_create(item: str):12- typer.echo(f"Creating item: {item}")12+ print(f"Creating item: {item}")13 14 15 @items_app.command("delete")16 def items_delete(item: str):17- typer.echo(f"Deleting item: {item}")17+ print(f"Deleting item: {item}")18 19 20 @items_app.command("sell")21 def items_sell(item: str):22- typer.echo(f"Selling item: {item}")22+ print(f"Selling item: {item}")23 24 25 @users_app.command("create")26 def users_create(user_name: str):27- typer.echo(f"Creating user: {user_name}")27+ print(f"Creating user: {user_name}")28 29 30 @users_app.command("delete")31 def users_delete(user_name: str):32- typer.echo(f"Deleting user: {user_name}")32+ print(f"Deleting user: {user_name}")33 34 35 if __name__ == "__main__":36 app()modified:docs_src/subcommands/tutorial003/items.py+3 added-3 removed
3 unmodified lines4 5 6 @app.command()7 def create(item: str):8- typer.echo(f"Creating item: {item}")8+ print(f"Creating item: {item}")9 10 11 @app.command()12 def delete(item: str):13- typer.echo(f"Deleting item: {item}")13+ print(f"Deleting item: {item}")14 15 16 @app.command()17 def sell(item: str):18- typer.echo(f"Selling item: {item}")18+ print(f"Selling item: {item}")19 20 21 if __name__ == "__main__":22 app()modified:docs_src/subcommands/tutorial003/reigns.py+2 added-2 removed
3 unmodified lines4 5 6 @app.command()7 def conquer(name: str):8- typer.echo(f"Conquering reign: {name}")8+ print(f"Conquering reign: {name}")9 10 11 @app.command()12 def destroy(name: str):13- typer.echo(f"Destroying reign: {name}")13+ print(f"Destroying reign: {name}")14 15 16 if __name__ == "__main__":17 app()modified:docs_src/subcommands/tutorial003/towns.py+2 added-2 removed
3 unmodified lines4 5 6 @app.command()7 def found(name: str):8- typer.echo(f"Founding town: {name}")8+ print(f"Founding town: {name}")9 10 11 @app.command()12 def burn(name: str):13- typer.echo(f"Burning town: {name}")13+ print(f"Burning town: {name}")14 15 16 if __name__ == "__main__":17 app()modified:docs_src/subcommands/tutorial003/users.py+2 added-2 removed
3 unmodified lines4 5 6 @app.command()7 def create(user_name: str):8- typer.echo(f"Creating user: {user_name}")8+ print(f"Creating user: {user_name}")9 10 11 @app.command()12 def delete(user_name: str):13- typer.echo(f"Deleting user: {user_name}")13+ print(f"Deleting user: {user_name}")14 15 16 if __name__ == "__main__":17 app()modified:docs_src/terminating/tutorial001.py+3 added-3 removed
3 unmodified lines4 5 6 def maybe_create_user(username: str):7 if username in existing_usernames:8- typer.echo("The user already exists")8+ print("The user already exists")9 raise typer.Exit()10 else:11- typer.echo(f"User created: {username}")11+ print(f"User created: {username}")12 13 14 def send_new_user_notification(username: str):15 # Somehow send a notification here for the new user, maybe an email16- typer.echo(f"Notification sent for new user: {username}")16+ print(f"Notification sent for new user: {username}")17 18 19 def main(username: str):20 maybe_create_user(username=username)5 unmodified linesmodified:docs_src/terminating/tutorial002.py+2 added-2 removed
1 unmodified line2 3 4 def main(username: str):5 if username == "root":6- typer.echo("The root user is reserved")6+ print("The root user is reserved")7 raise typer.Exit(code=1)8- typer.echo(f"New user created: {username}")8+ print(f"New user created: {username}")9 10 11 if __name__ == "__main__":12 typer.run(main)modified:docs_src/terminating/tutorial003.py+2 added-2 removed
1 unmodified line2 3 4 def main(username: str):5 if username == "root":6- typer.echo("The root user is reserved")6+ print("The root user is reserved")7 raise typer.Abort()8- typer.echo(f"New user created: {username}")8+ print(f"New user created: {username}")9 10 11 if __name__ == "__main__":12 typer.run(main)modified:docs_src/testing/app01/main.py+2 added-2 removed
5 unmodified lines6 7 8 @app.command()9 def main(name: str, city: Optional[str] = None):10- typer.echo(f"Hello {name}")10+ print(f"Hello {name}")11 if city:12- typer.echo(f"Let's have a coffee in {city}")12+ print(f"Let's have a coffee in {city}")13 14 15 if __name__ == "__main__":16 app()modified:docs_src/testing/app02/main.py+1 added-1 removed
3 unmodified lines4 5 6 @app.command()7 def main(name: str, email: str = typer.Option(..., prompt=True)):8- typer.echo(f"Hello {name}, your email is: {email}")8+ print(f"Hello {name}, your email is: {email}")9 10 11 if __name__ == "__main__":12 app()modified:docs_src/testing/app03/main.py+1 added-1 removed
1 import typer2 3 4 def main(name: str = "World"):5- typer.echo(f"Hello {name}")5+ print(f"Hello {name}")6 7 8 if __name__ == "__main__":9 typer.run(main)modified:docs_src/using_click/tutorial003.py+1 added-1 removed
7 unmodified lines8 def top():9 """10 Top level command, form Typer11 """12- typer.echo("The Typer app is at the top level")12+ print("The Typer app is at the top level")13 14 15 @app.callback()16 def callback():18 unmodified linesmodified:docs_src/using_click/tutorial004.py+1 added-1 removed
23 unmodified lines24 def sub():25 """26 A single-command Typer sub app27 """28- typer.echo("Typer is now below Click, the Click app is the top level")28+ print("Typer is now below Click, the Click app is the top level")29 30 31 typer_click_object = typer.main.get_command(app)32 4 unmodified linesmodified:scripts/test.sh+4 added
1 unmodified line2 3 set -e4 set -x5 6+# For tests, a large terminal width7+export TERMINAL_WIDTH=30008+# Force disable terminal for tests inside of pytest, takes precedence over GITHUB_ACTIONS env var9+export _TYPER_FORCE_DISABLE_TERMINAL=110 bash ./scripts/test-files.sh11 # Use xdist-pytest --forked to ensure modified sys.path to import relative modules in examples keeps working12 pytest --cov=typer --cov=tests --cov=docs_src --cov-report=term-missing --cov-report=xml -o console_output_style=progress --forked --numprocesses=auto ${@}modified:tests/assets/compat_click7_8.py+1 added-1 removed
20 unmodified lines21 ):22 """23 Say hello.24 """25- typer.echo(f"Hello {name} {lastname}, it seems you have {age}, {nickname}")25+ print(f"Hello {name} {lastname}, it seems you have {age}, {nickname}")26 27 28 if __name__ == "__main__":29 app()modified:tests/assets/completion_no_types_order.py+1 added-1 removed
14 unmodified lines15 16 17 @app.command()18 def main(name: str = typer.Option("World", autocompletion=complete)):19- typer.echo(f"Hello {name}")19+ print(f"Hello {name}")20 21 22 if __name__ == "__main__":23 app()modified:tests/assets/completion_no_types.py+1 added-1 removed
14 unmodified lines15 16 17 @app.command()18 def main(name: str = typer.Option("World", autocompletion=complete)):19- typer.echo(f"Hello {name}")19+ print(f"Hello {name}")20 21 22 if __name__ == "__main__":23 app()modified:tests/test_compat/test_option_get_help.py+14 added
1 import os2 import subprocess3 4+import typer.core5 from typer.testing import CliRunner6 7 from tests.assets import compat_click7_8 as mod8 9 unmodified lines18 assert "TEST_LASTNAME" in result.output19 assert "(dynamic)" in result.output20 21 22+def test_hidden_option_no_rich():23+ rich = typer.core.rich24+ typer.core.rich = None25+ result = runner.invoke(mod.app, ["--help"])26+ assert result.exit_code == 027+ assert "Say hello" in result.output28+ assert "--name" not in result.output29+ assert "/lastname" in result.output30+ assert "TEST_LASTNAME" in result.output31+ assert "(dynamic)" in result.output32+ typer.core.rich = rich33+34+35 def test_coverage_call():36 result = runner.invoke(mod.app)37 assert result.exit_code == 038 assert "Hello John Doe, it seems you have 42" in result.output17 unmodified linesmodified:tests/test_completion/test_completion_install.py+2 added-2 removed
26 unmodified lines27 },28 )29 # TODO: when deprecating Click 7, remove second option30 assert (31- "Error: Option '--install-completion' requires an argument" in result.stderr32- or "Error: --install-completion option requires an argument" in result.stderr31+ "Option '--install-completion' requires an argument" in result.stderr32+ or "--install-completion option requires an argument" in result.stderr33 )34 35 36 def test_completion_install_bash():121 unmodified linesmodified:tests/test_completion/test_completion_show.py+2 added-2 removed
16 unmodified lines17 },18 )19 # TODO: when deprecating Click 7, remove second option20 assert (21- "Error: Option '--show-completion' requires an argument" in result.stderr22- or "Error: --show-completion option requires an argument" in result.stderr21+ "Option '--show-completion' requires an argument" in result.stderr22+ or "--show-completion option requires an argument" in result.stderr23 )24 25 26 def test_completion_show_bash():81 unmodified linesmodified:tests/test_tutorial/test_arguments/test_default/test_tutorial001.py+1 added-1 removed
13 unmodified lines14 def test_help():15 result = runner.invoke(app, ["--help"])16 assert result.exit_code == 017 assert "[OPTIONS] [NAME]" in result.output18- assert "Arguments:" in result.output18+ assert "Arguments" in result.output19 assert "[default: Wade Wilson]" in result.output20 21 22 def test_call_no_arg():19 unmodified linesmodified:tests/test_tutorial/test_arguments/test_default/test_tutorial002.py+1 added-1 removed
13 unmodified lines14 def test_help():15 result = runner.invoke(app, ["--help"])16 assert result.exit_code == 017 assert "[OPTIONS] [NAME]" in result.output18- assert "Arguments:" in result.output18+ assert "Arguments" in result.output19 assert "[default: (dynamic)]" in result.output20 21 22 def test_call_no_arg():21 unmodified linesmodified:tests/test_tutorial/test_arguments/test_envvar/test_tutorial001.py+16 added-2 removed
1 import subprocess2 3 import typer4+import typer.core5 from typer.testing import CliRunner6 7 from docs_src.arguments.envvar import tutorial001 as mod8 6 unmodified lines15 def test_help():16 result = runner.invoke(app, ["--help"])17 assert result.exit_code == 018 assert "[OPTIONS] [NAME]" in result.output18- assert "Arguments:" in result.output19- assert "[env var: AWESOME_NAME;default: World]" in result.output19+ assert "Arguments" in result.output20+ assert "env var: AWESOME_NAME" in result.output21+ assert "default: World" in result.output22 23 24+def test_help_no_rich():25+ rich = typer.core.rich26+ typer.core.rich = None27+ result = runner.invoke(app, ["--help"])28+ assert result.exit_code == 029+ assert "[OPTIONS] [NAME]" in result.output30+ assert "Arguments" in result.output31+ assert "env var: AWESOME_NAME" in result.output32+ assert "default: World" in result.output33+ typer.core.rich = rich34+35+36 def test_call_arg():37 result = runner.invoke(app, ["Wednesday"])38 assert result.exit_code == 039 assert "Hello Mr. Wednesday" in result.output22 unmodified linesmodified:tests/test_tutorial/test_arguments/test_envvar/test_tutorial002.py+3 added-2 removed
13 unmodified lines14 def test_help():15 result = runner.invoke(app, ["--help"])16 assert result.exit_code == 017 assert "[OPTIONS] [NAME]" in result.output18- assert "Arguments:" in result.output19- assert "[env var: AWESOME_NAME, GOD_NAME;default: World]" in result.output18+ assert "Arguments" in result.output19+ assert "env var: AWESOME_NAME, GOD_NAME" in result.output20+ assert "default: World" in result.output21 22 23 def test_call_arg():24 result = runner.invoke(app, ["Wednesday"])24 unmodified linesmodified:tests/test_tutorial/test_arguments/test_envvar/test_tutorial003.py+3 added-3 removed
13 unmodified lines14 def test_help():15 result = runner.invoke(app, ["--help"])16 assert result.exit_code == 017 assert "[OPTIONS] [NAME]" in result.output18- assert "Arguments:" in result.output19- assert "[env var: AWESOME_NAME;default: World]" not in result.output20- assert "[default: World]" in result.output18+ assert "Arguments" in result.output19+ assert "env var: AWESOME_NAME" not in result.output20+ assert "default: World" in result.output21 22 23 def test_call_arg():24 result = runner.invoke(app, ["Wednesday"])24 unmodified linesmodified:tests/test_tutorial/test_arguments/test_help/test_tutorial001.py+15 added-1 removed
1 import subprocess2 3 import typer4+import typer.core5 from typer.testing import CliRunner6 7 from docs_src.arguments.help import tutorial001 as mod8 6 unmodified lines15 def test_help():16 result = runner.invoke(app, ["--help"])17 assert result.exit_code == 018 assert "[OPTIONS] NAME" in result.output18- assert "Arguments:" in result.output19+ assert "Arguments" in result.output20 assert "NAME" in result.output21 assert "The name of the user to greet" in result.output22 assert "[required]" in result.output23 24 25+def test_help_no_rich():26+ rich = typer.core.rich27+ typer.core.rich = None28+ result = runner.invoke(app, ["--help"])29+ assert result.exit_code == 030+ assert "[OPTIONS] NAME" in result.output31+ assert "Arguments" in result.output32+ assert "NAME" in result.output33+ assert "The name of the user to greet" in result.output34+ assert "[required]" in result.output35+ typer.core.rich = rich36+37+38 def test_call_arg():39 result = runner.invoke(app, ["Camila"])40 assert result.exit_code == 041 assert "Hello Camila" in result.output10 unmodified linesmodified:tests/test_tutorial/test_arguments/test_help/test_tutorial002.py+1 added-1 removed
14 unmodified lines15 result = runner.invoke(app, ["--help"])16 assert result.exit_code == 017 assert "[OPTIONS] NAME" in result.output18 assert "Say hi to NAME very gently, like Dirk." in result.output19- assert "Arguments:" in result.output19+ assert "Arguments" in result.output20 assert "NAME" in result.output21 assert "The name of the user to greet" in result.output22 assert "[required]" in result.output23 15 unmodified linesmodified:tests/test_tutorial/test_arguments/test_help/test_tutorial003.py+1 added-1 removed
14 unmodified lines15 result = runner.invoke(app, ["--help"])16 assert result.exit_code == 017 assert "[OPTIONS] [NAME]" in result.output18 assert "Say hi to NAME very gently, like Dirk." in result.output19- assert "Arguments:" in result.output19+ assert "Arguments" in result.output20 assert "NAME" in result.output21 assert "Who to greet" in result.output22 assert "[default: World]" in result.output23 15 unmodified linesmodified:tests/test_tutorial/test_arguments/test_help/test_tutorial004.py+1 added-1 removed
14 unmodified lines15 result = runner.invoke(app, ["--help"])16 assert result.exit_code == 017 assert "[OPTIONS] [NAME]" in result.output18 assert "Say hi to NAME very gently, like Dirk." in result.output19- assert "Arguments:" in result.output19+ assert "Arguments" in result.output20 assert "NAME" in result.output21 assert "Who to greet" in result.output22 assert "[default: World]" not in result.output23 15 unmodified linesmodified:tests/test_tutorial/test_arguments/test_help/test_tutorial005.py+1 added-1 removed
13 unmodified lines14 def test_help():15 result = runner.invoke(app, ["--help"])16 assert result.exit_code == 017 assert "[OPTIONS] [NAME]" in result.output18- assert "Arguments:" in result.output18+ assert "Arguments" in result.output19 assert "Who to greet" in result.output20 assert "[default: (Deadpoolio the amazing's name)]" in result.output21 22 14 unmodified linesmodified:tests/test_tutorial/test_arguments/test_help/test_tutorial006.py+1 added-1 removed
13 unmodified lines14 def test_help():15 result = runner.invoke(app, ["--help"])16 assert result.exit_code == 017 assert "[OPTIONS] ✨username✨" in result.output18- assert "Arguments:" in result.output18+ assert "Arguments" in result.output19 assert "✨username✨" in result.output20 assert "[default: World]" in result.output21 22 14 unmodified linesmodified:tests/test_tutorial/test_arguments/test_help/test_tutorial007.py+3 added-3 removed
1 import subprocess2 3 import typer4+import typer.core5 from typer.testing import CliRunner6 7 from docs_src.arguments.help import tutorial007 as mod8 5 unmodified lines14 15 def test_help():16 result = runner.invoke(app, ["--help"])17 assert result.exit_code == 017- assert "[OPTIONS] [NAME]" in result.output18 assert "Say hi to NAME very gently, like Dirk." in result.output19- assert "Arguments:" not in result.output20- assert "[default: World]" not in result.output19+ assert "Arguments" in result.output20+ assert "Secondary Arguments" in result.output21 22 23 def test_call_arg():24 result = runner.invoke(app, ["Camila"])12 unmodified linesadded:tests/test_tutorial/test_arguments/test_help/test_tutorial008.py+49 added
1+import subprocess2+3+import typer4+import typer.core5+from typer.testing import CliRunner6+7+from docs_src.arguments.help import tutorial008 as mod8+9+runner = CliRunner()10+11+app = typer.Typer()12+app.command()(mod.main)13+14+15+def test_help():16+ result = runner.invoke(app, ["--help"])17+ assert result.exit_code == 018+ assert "[OPTIONS] [NAME]" in result.output19+ assert "Say hi to NAME very gently, like Dirk." in result.output20+ assert "Arguments" not in result.output21+ assert "[default: World]" not in result.output22+23+24+def test_help_no_rich():25+ rich = typer.core.rich26+ typer.core.rich = None27+ result = runner.invoke(app, ["--help"])28+ assert result.exit_code == 029+ assert "[OPTIONS] [NAME]" in result.output30+ assert "Say hi to NAME very gently, like Dirk." in result.output31+ assert "Arguments" not in result.output32+ assert "[default: World]" not in result.output33+ typer.core.rich = rich34+35+36+def test_call_arg():37+ result = runner.invoke(app, ["Camila"])38+ assert result.exit_code == 039+ assert "Hello Camila" in result.output40+41+42+def test_script():43+ result = subprocess.run(44+ ["coverage", "run", mod.__file__, "--help"],45+ stdout=subprocess.PIPE,46+ stderr=subprocess.PIPE,47+ encoding="utf-8",48+ )49+ assert "Usage" in result.stdoutmodified:tests/test_tutorial/test_arguments/test_optional/test_tutorial001.py+18 added-1 removed
1 import subprocess2 3 import typer4+import typer.core5 from typer.testing import CliRunner6 7 from docs_src.arguments.optional import tutorial001 as mod8 5 unmodified lines14 15 def test_call_no_arg():16 result = runner.invoke(app)17 assert result.exit_code != 017- assert "Error: Missing argument 'NAME'." in result.output18+ assert "Missing argument 'NAME'." in result.output19 20 21+def test_call_no_arg_standalone():22+ # Mainly for coverage23+ result = runner.invoke(app, standalone_mode=False)24+ assert result.exit_code != 025+26+27+def test_call_no_arg_no_rich():28+ # Mainly for coverage29+ rich = typer.core.rich30+ typer.core.rich = None31+ result = runner.invoke(app)32+ assert result.exit_code != 033+ assert "Error: Missing argument 'NAME'" in result.stdout34+ typer.core.rich = rich35+36+37 def test_call_arg():38 result = runner.invoke(app, ["Camila"])39 assert result.exit_code == 040 assert "Hello Camila" in result.output10 unmodified linesmodified:tests/test_tutorial/test_commands/test_callback/test_tutorial001.py+16 added-3 removed
1 import subprocess2 3+import typer.core4 from typer.testing import CliRunner5 6 from docs_src.commands.callback import tutorial001 as mod7 5 unmodified lines13 def test_help():14 result = runner.invoke(app, ["--help"])15 assert result.exit_code == 016 assert "Manage users in the awesome CLI app." in result.output16- assert "--verbose / --no-verbose" in result.output17+ assert "--verbose" in result.output18+ assert "--no-verbose" in result.output19 20 21+def test_help_no_rich():22+ rich = typer.core.rich23+ typer.core.rich = None24+ result = runner.invoke(app, ["--help"])25+ assert result.exit_code == 026+ assert "Manage users in the awesome CLI app." in result.output27+ assert "--verbose" in result.output28+ assert "--no-verbose" in result.output29+ typer.core.rich = rich30+31+32 def test_create():33 result = runner.invoke(app, ["create", "Camila"])34 assert result.exit_code == 035 assert "Creating user: Camila" in result.output27 unmodified lines63 result = runner.invoke(app, ["delete", "--verbose", "Camila"])64 assert result.exit_code != 065 # TODO: when deprecating Click 7, remove second option66 assert (54- "Error: No such option: --verbose" in result.output55- or "Error: no such option: --verbose" in result.output67+ "No such option: --verbose" in result.output68+ or "no such option: --verbose" in result.output69 )70 71 72 def test_script():7 unmodified linesmodified:tests/test_tutorial/test_commands/test_help/test_tutorial001.py+4 added-2 removed
33 unmodified lines34 result = runner.invoke(app, ["delete", "--help"])35 assert result.exit_code == 036 assert "delete [OPTIONS] USERNAME" in result.output37 assert "Delete a user with USERNAME." in result.output38- assert "--force / --no-force" in result.output38+ assert "--force" in result.output39+ assert "--no-force" in result.output40 assert "Force deletion without confirmation." in result.output41 42 43 def test_help_delete_all():2 unmodified lines46 assert "delete-all [OPTIONS]" in result.output47 assert "Delete ALL users in the database." in result.output48 assert "If --force is not used, will ask for confirmation." in result.output49 assert "[required]" in result.output49- assert "--force / --no-force" in result.output50+ assert "--force" in result.output51+ assert "--no-force" in result.output52 assert "Force deletion without confirmation." in result.output53 54 55 def test_help_init():70 unmodified linesadded:tests/test_tutorial/test_commands/test_help/test_tutorial003.py+44 added
1+import subprocess2+3+from typer.testing import CliRunner4+5+from docs_src.commands.help import tutorial003 as mod6+7+app = mod.app8+9+runner = CliRunner()10+11+12+def test_help():13+ result = runner.invoke(app, ["--help"])14+ assert result.exit_code == 015+ assert "create" in result.output16+ assert "Create a user." in result.output17+ assert "delete" in result.output18+ assert "(deprecated)" in result.output19+ assert "Delete a user." in result.output20+21+22+def test_help_delete():23+ result = runner.invoke(app, ["delete", "--help"])24+ assert result.exit_code == 025+ assert "(deprecated)" in result.output26+ assert "Delete a user." in result.output27+28+29+def test_call():30+ # Mainly for coverage31+ result = runner.invoke(app, ["create", "Camila"])32+ assert result.exit_code == 033+ result = runner.invoke(app, ["delete", "Camila"])34+ assert result.exit_code == 035+36+37+def test_script():38+ result = subprocess.run(39+ ["coverage", "run", mod.__file__, "--help"],40+ stdout=subprocess.PIPE,41+ stderr=subprocess.PIPE,42+ encoding="utf-8",43+ )44+ assert "Usage" in result.stdoutadded:tests/test_tutorial/test_commands/test_help/test_tutorial004.py+59 added
1+import subprocess2+3+from typer.testing import CliRunner4+5+from docs_src.commands.help import tutorial004 as mod6+7+app = mod.app8+9+runner = CliRunner()10+11+12+def test_help():13+ result = runner.invoke(app, ["--help"])14+ assert result.exit_code == 015+ assert "create" in result.output16+ assert "Create a new shinny user. ✨" in result.output17+ assert "delete" in result.output18+ assert "Delete a user with USERNAME." in result.output19+ assert "Some internal utility function to create." not in result.output20+ assert "Some internal utility function to delete." not in result.output21+22+23+def test_help_create():24+ result = runner.invoke(app, ["create", "--help"])25+ assert result.exit_code == 026+ assert "Create a new shinny user. ✨" in result.output27+ assert "The username to be created" in result.output28+ assert "Some internal utility function to create." not in result.output29+30+31+def test_help_delete():32+ result = runner.invoke(app, ["delete", "--help"])33+ assert result.exit_code == 034+ assert "Delete a user with USERNAME." in result.output35+ assert "The username to be deleted" in result.output36+ assert "Force the deletion 💥" in result.output37+ assert "Some internal utility function to delete." not in result.output38+39+40+def test_create():41+ result = runner.invoke(app, ["create", "Camila"])42+ assert result.exit_code == 043+ assert "Creating user: Camila" in result.output44+45+46+def test_delete():47+ result = runner.invoke(app, ["delete", "Camila"])48+ assert result.exit_code == 049+ assert "Deleting user: Camila" in result.output50+51+52+def test_script():53+ result = subprocess.run(54+ ["coverage", "run", mod.__file__, "--help"],55+ stdout=subprocess.PIPE,56+ stderr=subprocess.PIPE,57+ encoding="utf-8",58+ )59+ assert "Usage" in result.stdoutadded:tests/test_tutorial/test_commands/test_help/test_tutorial005.py+60 added
1+import subprocess2+3+from typer.testing import CliRunner4+5+from docs_src.commands.help import tutorial005 as mod6+7+app = mod.app8+9+runner = CliRunner()10+11+12+def test_help():13+ result = runner.invoke(app, ["--help"])14+ assert result.exit_code == 015+ assert "create" in result.output16+ assert "Create a new shinny user. ✨" in result.output17+ assert "delete" in result.output18+ assert "Delete a user with USERNAME." in result.output19+ assert "Some internal utility function to create." not in result.output20+ assert "Some internal utility function to delete." not in result.output21+22+23+def test_help_create():24+ result = runner.invoke(app, ["create", "--help"])25+ assert result.exit_code == 026+ assert "Create a new shinny user. ✨" in result.output27+ assert "The username to be created" in result.output28+ assert "Learn more at the Typer docs website" in result.output29+ assert "Some internal utility function to create." not in result.output30+31+32+def test_help_delete():33+ result = runner.invoke(app, ["delete", "--help"])34+ assert result.exit_code == 035+ assert "Delete a user with USERNAME." in result.output36+ assert "The username to be deleted" in result.output37+ assert "Force the deletion 💥" in result.output38+ assert "Some internal utility function to delete." not in result.output39+40+41+def test_create():42+ result = runner.invoke(app, ["create", "Camila"])43+ assert result.exit_code == 044+ assert "Creating user: Camila" in result.output45+46+47+def test_delete():48+ result = runner.invoke(app, ["delete", "Camila"])49+ assert result.exit_code == 050+ assert "Deleting user: Camila" in result.output51+52+53+def test_script():54+ result = subprocess.run(55+ ["coverage", "run", mod.__file__, "--help"],56+ stdout=subprocess.PIPE,57+ stderr=subprocess.PIPE,58+ encoding="utf-8",59+ )60+ assert "Usage" in result.stdoutadded:tests/test_tutorial/test_commands/test_help/test_tutorial006.py+51 added
1+import subprocess2+3+from typer.testing import CliRunner4+5+from docs_src.commands.help import tutorial006 as mod6+7+app = mod.app8+9+runner = CliRunner()10+11+12+def test_main_help():13+ result = runner.invoke(app, ["--help"])14+ assert result.exit_code == 015+ assert "create" in result.output16+ assert "Create a new user. ✨" in result.output17+ assert "delete" in result.output18+ assert "Delete a user. 🔥" in result.output19+ assert "Utils and Configs" in result.output20+ assert "config" in result.output21+ assert "Configure the system. 🔧" in result.output22+ assert "Synchronize the system or something fancy like that. ♻" in result.output23+ assert "Help and Others" in result.output24+ assert "Get help with the system. ❓" in result.output25+ assert "Report an issue. 🐛" in result.output26+27+28+def test_call():29+ # Mainly for coverage30+ result = runner.invoke(app, ["create", "Morty"])31+ assert result.exit_code == 032+ result = runner.invoke(app, ["delete", "Morty"])33+ assert result.exit_code == 034+ result = runner.invoke(app, ["config", "Morty"])35+ assert result.exit_code == 036+ result = runner.invoke(app, ["sync"])37+ assert result.exit_code == 038+ result = runner.invoke(app, ["help"])39+ assert result.exit_code == 040+ result = runner.invoke(app, ["report"])41+ assert result.exit_code == 042+43+44+def test_script():45+ result = subprocess.run(46+ ["coverage", "run", mod.__file__, "--help"],47+ stdout=subprocess.PIPE,48+ stderr=subprocess.PIPE,49+ encoding="utf-8",50+ )51+ assert "Usage" in result.stdoutadded:tests/test_tutorial/test_commands/test_help/test_tutorial007.py+55 added
1+import subprocess2+3+from typer.testing import CliRunner4+5+from docs_src.commands.help import tutorial007 as mod6+7+app = mod.app8+9+runner = CliRunner()10+11+12+def test_main_help():13+ result = runner.invoke(app, ["--help"])14+ assert result.exit_code == 015+ assert "create" in result.output16+ assert "Create a new user. ✨" in result.output17+ assert "Utils and Configs" in result.output18+ assert "config" in result.output19+ assert "Configure the system. 🔧" in result.output20+21+22+def test_create_help():23+ result = runner.invoke(app, ["create", "--help"])24+ assert result.exit_code == 025+ assert "username" in result.output26+ assert "The username to create" in result.output27+ assert "Secondary Arguments" in result.output28+ assert "lastname" in result.output29+ assert "The last name of the new user" in result.output30+ assert "--force" in result.output31+ assert "--no-force" in result.output32+ assert "Force the creation of the user" in result.output33+ assert "Additional Data" in result.output34+ assert "--age" in result.output35+ assert "The age of the new user" in result.output36+ assert "--favorite-color" in result.output37+ assert "The favorite color of the new user" in result.output38+39+40+def test_call():41+ # Mainly for coverage42+ result = runner.invoke(app, ["create", "Morty"])43+ assert result.exit_code == 044+ result = runner.invoke(app, ["config", "Morty"])45+ assert result.exit_code == 046+47+48+def test_script():49+ result = subprocess.run(50+ ["coverage", "run", mod.__file__, "--help"],51+ stdout=subprocess.PIPE,52+ stderr=subprocess.PIPE,53+ encoding="utf-8",54+ )55+ assert "Usage" in result.stdoutadded:tests/test_tutorial/test_commands/test_help/test_tutorial008.py+32 added
1+import subprocess2+3+from typer.testing import CliRunner4+5+from docs_src.commands.help import tutorial008 as mod6+7+app = mod.app8+9+runner = CliRunner()10+11+12+def test_main_help():13+ result = runner.invoke(app, ["--help"])14+ assert result.exit_code == 015+ assert "Create a new user. ✨" in result.output16+ assert "Made with ❤ in Venus" in result.output17+18+19+def test_call():20+ # Mainly for coverage21+ result = runner.invoke(app, ["Morty"])22+ assert result.exit_code == 023+24+25+def test_script():26+ result = subprocess.run(27+ ["coverage", "run", mod.__file__, "--help"],28+ stdout=subprocess.PIPE,29+ stderr=subprocess.PIPE,30+ encoding="utf-8",31+ )32+ assert "Usage" in result.stdoutmodified:tests/test_tutorial/test_commands/test_index/test_tutorial001.py+1 added-1 removed
10 unmodified lines11 12 def test_no_arg():13 result = runner.invoke(app)14 assert result.exit_code != 015- assert "Error: Missing argument 'NAME'." in result.output15+ assert "Missing argument 'NAME'." in result.output16 17 18 def test_arg():19 result = runner.invoke(app, ["Camila"])12 unmodified linesmodified:tests/test_tutorial/test_commands/test_index/test_tutorial002.py+1 added-1 removed
11 unmodified lines12 def test_help():13 result = runner.invoke(app, ["--help"])14 assert result.exit_code == 015 assert "[OPTIONS] COMMAND [ARGS]..." in result.output16- assert "Commands:" in result.output16+ assert "Commands" in result.output17 assert "create" in result.output18 assert "delete" in result.output19 20 20 unmodified linesmodified:tests/test_tutorial/test_commands/test_name/test_tutorial001.py+1 added-1 removed
10 unmodified lines11 12 def test_help():13 result = runner.invoke(app, ["--help"])14 assert result.exit_code == 015- assert "Commands:" in result.output15+ assert "Commands" in result.output16 assert "create" in result.output17 assert "delete" in result.output18 19 20 unmodified linesmodified:tests/test_tutorial/test_commands/test_one_or_multiple/test_tutorial001.py+1 added-1 removed
10 unmodified lines11 12 def test_help():13 result = runner.invoke(app, ["--help"])14 assert result.exit_code == 015- assert "Commands:" in result.output15+ assert "Commands" in result.output16 assert "create" in result.output17 18 19 def test_command():13 unmodified linesmodified:tests/test_tutorial/test_commands/test_one_or_multiple/test_tutorial002.py+1 added-1 removed
12 unmodified lines13 result = runner.invoke(app, ["--help"])14 assert result.exit_code == 015 assert "Creates a single user Hiro Hamada." in result.output16 assert "In the next version it will create 5 users more." in result.output17- assert "Commands:" in result.output17+ assert "Commands" in result.output18 assert "create" in result.output19 20 21 def test_command():13 unmodified linesmodified:tests/test_tutorial/test_commands/test_options/test_tutorial001.py+1 added-1 removed
10 unmodified lines11 12 def test_help():13 result = runner.invoke(app, ["--help"])14 assert result.exit_code == 015- assert "Commands:" in result.output15+ assert "Commands" in result.output16 assert "create" in result.output17 assert "delete" in result.output18 assert "delete-all" in result.output19 assert "init" in result.output77 unmodified linesmodified:tests/test_tutorial/test_first_steps/test_tutorial002.py+1 added-1 removed
12 unmodified lines13 14 def test_1():15 result = runner.invoke(app, [])16 assert result.exit_code != 017- assert "Error: Missing argument 'NAME'" in result.output17+ assert "Missing argument 'NAME'" in result.output18 19 20 def test_2():21 result = runner.invoke(app, ["Camila"])12 unmodified linesmodified:tests/test_tutorial/test_first_steps/test_tutorial003.py+1 added-1 removed
12 unmodified lines13 14 def test_1():15 result = runner.invoke(app, ["Camila"])16 assert result.exit_code != 017- assert "Error: Missing argument 'LASTNAME'" in result.output17+ assert "Missing argument 'LASTNAME'" in result.output18 19 20 def test_2():21 result = runner.invoke(app, ["Camila", "Gutiérrez"])12 unmodified linesmodified:tests/test_tutorial/test_first_steps/test_tutorial004.py+7 added-4 removed
12 unmodified lines13 14 def test_help():15 result = runner.invoke(app, ["--help"])16 assert result.exit_code == 017- assert "Arguments:" in result.output18- assert "NAME [required]" in result.output19- assert "LASTNAME [required]" in result.output20- assert "--formal / --no-formal" in result.output17+ assert "Arguments" in result.output18+ assert "NAME" in result.output19+ assert "[required]" in result.output20+ assert "LASTNAME" in result.output21+ assert "[required]" in result.output22+ assert "--formal" in result.output23+ assert "--no-formal" in result.output24 25 26 def test_1():27 result = runner.invoke(app, ["Camila", "Gutiérrez"])30 unmodified linesmodified:tests/test_tutorial/test_first_steps/test_tutorial005.py+7 added-4 removed
12 unmodified lines13 14 def test_help():15 result = runner.invoke(app, ["--help"])16 assert result.exit_code == 017- assert "Arguments:" in result.output18- assert "NAME [required]" in result.output19- assert "--lastname TEXT" in result.output20- assert "--formal / --no-formal" in result.output17+ assert "Arguments" in result.output18+ assert "NAME" in result.output19+ assert "[required]" in result.output20+ assert "--lastname" in result.output21+ assert "TEXT" in result.output22+ assert "--formal" in result.output23+ assert "--no-formal" in result.output24 25 26 def test_1():27 result = runner.invoke(app, ["Camila"])30 unmodified linesmodified:tests/test_tutorial/test_multiple_values/test_arguments_with_multiple_values/test_tutorial002.py+3 added-3 removed
12 unmodified lines13 def test_help():14 result = runner.invoke(app, ["--help"])15 assert result.exit_code == 016 assert "[OPTIONS] [NAMES]..." in result.output17- assert "Arguments:" in result.output17+ assert "Arguments" in result.output18 assert "[default: Harry, Hermione, Ron]" in result.output19 20 21 def test_defaults():9 unmodified lines31 assert result.exit_code != 032 # TODO: when deprecating Click 7, remove second option33 34 assert (35- "Error: Argument 'names' takes 3 values" in result.stdout36- or "Error: argument names takes 3 values" in result.stdout35+ "Argument 'names' takes 3 values" in result.stdout36+ or "argument names takes 3 values" in result.stdout37 )38 39 40 def test_valid_args():15 unmodified linesmodified:tests/test_tutorial/test_multiple_values/test_multiple_options/test_tutorial001.py+1 added-1 removed
12 unmodified lines13 def test_main():14 result = runner.invoke(app)15 assert result.exit_code != 016 assert "No provided users" in result.output17- assert "Aborted!" in result.output17+ assert "Aborted" in result.output18 19 20 def test_1_user():21 result = runner.invoke(app, ["--user", "Camila"])22 unmodified linesmodified:tests/test_tutorial/test_multiple_values/test_options_with_multiple_values/test_tutorial001.py+3 added-3 removed
12 unmodified lines13 def test_main():14 result = runner.invoke(app)15 assert result.exit_code != 016 assert "No user provided" in result.output17- assert "Aborted!" in result.output17+ assert "Aborted" in result.output18 19 20 def test_user_1():21 result = runner.invoke(app, ["--user", "Camila", "50", "yes"])14 unmodified lines36 assert result.exit_code != 037 # TODO: when deprecating Click 7, remove second option38 39 assert (40- "Error: Option '--user' requires 3 arguments" in result.output41- or "Error: --user option requires 3 arguments" in result.output40+ "Option '--user' requires 3 arguments" in result.output41+ or "--user option requires 3 arguments" in result.output42 )43 44 45 def test_script():7 unmodified linesmodified:tests/test_tutorial/test_options/test_callback/test_tutorial001.py+1 added-1 removed
18 unmodified lines19 20 def test_2():21 result = runner.invoke(app, ["--name", "rick"])22 assert result.exit_code != 023- assert "Error: Invalid value for '--name': Only Camila is allowed" in result.output23+ assert "Invalid value for '--name': Only Camila is allowed" in result.output24 25 26 def test_script():27 result = subprocess.run(6 unmodified linesmodified:tests/test_tutorial/test_options/test_callback/test_tutorial003.py+1 added-1 removed
20 unmodified lines21 22 def test_2():23 result = runner.invoke(app, ["--name", "rick"])24 assert result.exit_code != 025- assert "Error: Invalid value for '--name': Only Camila is allowed" in result.output25+ assert "Invalid value for '--name': Only Camila is allowed" in result.output26 27 28 def test_script():29 result = subprocess.run(23 unmodified linesmodified:tests/test_tutorial/test_options/test_callback/test_tutorial004.py+1 added-1 removed
20 unmodified lines21 22 def test_2():23 result = runner.invoke(app, ["--name", "rick"])24 assert result.exit_code != 025- assert "Error: Invalid value for '--name': Only Camila is allowed" in result.output25+ assert "Invalid value for '--name': Only Camila is allowed" in result.output26 27 28 def test_script():29 result = subprocess.run(23 unmodified linesmodified:tests/test_tutorial/test_options/test_help/test_tutorial002.py+14 added-4 removed
10 unmodified lines11 app.command()(mod.main)12 13 14 def test_call():15- result = runner.invoke(app)15+ result = runner.invoke(app, ["World"])16 assert result.exit_code == 017- assert "Hello Wade Wilson" in result.output17+ assert "Hello World" in result.output18 19 20+def test_formal():21+ result = runner.invoke(app, ["World", "--formal"])22+ assert result.exit_code == 023+ assert "Good day Ms. World" in result.output24+25+26 def test_help():27 result = runner.invoke(app, ["--help"])28 assert result.exit_code == 023- assert "--fullname TEXT" in result.output24- assert "[default: Wade Wilson]" not in result.output29+ assert "--lastname" in result.output30+ assert "Customization and Utils" in result.output31+ assert "--formal" in result.output32+ assert "--no-formal" in result.output33+ assert "--debug" in result.output34+ assert "--no-debug" in result.output35 36 37 def test_script():38 result = subprocess.run(6 unmodified linesadded:tests/test_tutorial/test_options/test_help/test_tutorial003.py+35 added
1+import subprocess2+3+import typer4+from typer.testing import CliRunner5+6+from docs_src.options.help import tutorial003 as mod7+8+runner = CliRunner()9+10+app = typer.Typer()11+app.command()(mod.main)12+13+14+def test_call():15+ result = runner.invoke(app)16+ assert result.exit_code == 017+ assert "Hello Wade Wilson" in result.output18+19+20+def test_help():21+ result = runner.invoke(app, ["--help"])22+ assert result.exit_code == 023+ assert "--fullname" in result.output24+ assert "TEXT" in result.output25+ assert "[default: Wade Wilson]" not in result.output26+27+28+def test_script():29+ result = subprocess.run(30+ ["coverage", "run", mod.__file__, "--help"],31+ stdout=subprocess.PIPE,32+ stderr=subprocess.PIPE,33+ encoding="utf-8",34+ )35+ assert "Usage" in result.stdoutmodified:tests/test_tutorial/test_options/test_name/test_tutorial001.py+2 added-1 removed
12 unmodified lines13 14 def test_option_help():15 result = runner.invoke(app, ["--help"])16 assert result.exit_code == 017- assert "--name TEXT" in result.output17+ assert "--name" in result.output18+ assert "TEXT" in result.output19 assert "--user-name" not in result.output20 21 22 def test_call():13 unmodified linesmodified:tests/test_tutorial/test_options/test_name/test_tutorial002.py+3 added-1 removed
12 unmodified lines13 14 def test_option_help():15 result = runner.invoke(app, ["--help"])16 assert result.exit_code == 017- assert "-n, --name TEXT" in result.output17+ assert "-n" in result.output18+ assert "--name" in result.output19+ assert "TEXT" in result.output20 assert "--user-name" not in result.output21 22 23 def test_call():19 unmodified linesmodified:tests/test_tutorial/test_options/test_name/test_tutorial003.py+2 added-1 removed
12 unmodified lines13 14 def test_option_help():15 result = runner.invoke(app, ["--help"])16 assert result.exit_code == 017- assert "-n TEXT" in result.output17+ assert "-n" in result.output18+ assert "TEXT" in result.output19 assert "--user-name" not in result.output20 assert "--name" not in result.output21 22 14 unmodified linesmodified:tests/test_tutorial/test_options/test_name/test_tutorial004.py+3 added-1 removed
12 unmodified lines13 14 def test_option_help():15 result = runner.invoke(app, ["--help"])16 assert result.exit_code == 017- assert "-n, --user-name TEXT" in result.output17+ assert "-n" in result.output18+ assert "--user-name" in result.output19+ assert "TEXT" in result.output20 assert "--name" not in result.output21 22 23 def test_call():19 unmodified linesmodified:tests/test_tutorial/test_options/test_name/test_tutorial005.py+5 added-2 removed
12 unmodified lines13 14 def test_option_help():15 result = runner.invoke(app, ["--help"])16 assert result.exit_code == 017- assert "-n, --name TEXT" in result.output18- assert "-f, --formal" in result.output17+ assert "-n" in result.output18+ assert "--name" in result.output19+ assert "TEXT" in result.output20+ assert "-f" in result.output21+ assert "--formal" in result.output22 23 24 def test_call():25 result = runner.invoke(app, ["-n", "Camila"])29 unmodified linesmodified:tests/test_tutorial/test_options/test_prompt/test_tutorial001.py+2 added-1 removed
25 unmodified lines26 27 def test_help():28 result = runner.invoke(app, ["--help"])29 assert result.exit_code == 030- assert "--lastname TEXT" in result.output30+ assert "--lastname" in result.output31+ assert "TEXT" in result.output32 assert "[required]" in result.output33 34 35 def test_script():7 unmodified linesmodified:tests/test_tutorial/test_options/test_prompt/test_tutorial002.py+2 added-1 removed
25 unmodified lines26 27 def test_help():28 result = runner.invoke(app, ["--help"])29 assert result.exit_code == 030- assert "--lastname TEXT" in result.output30+ assert "--lastname" in result.output31+ assert "TEXT" in result.output32 assert "[required]" in result.output33 34 35 def test_script():7 unmodified linesmodified:tests/test_tutorial/test_options/test_prompt/test_tutorial003.py+2 added-1 removed
39 unmodified lines40 41 def test_help():42 result = runner.invoke(app, ["--help"])43 assert result.exit_code == 044- assert "--project-name TEXT" in result.output44+ assert "--project-name" in result.output45+ assert "TEXT" in result.output46 assert "[required]" in result.output47 48 49 def test_script():7 unmodified linesmodified:tests/test_tutorial/test_options/test_required/test_tutorial002.py+15 added-2 removed
1 import subprocess2 3 import typer4+import typer.core5 from typer.testing import CliRunner6 7 from docs_src.options.required import tutorial001 as mod8 5 unmodified lines14 15 def test_1():16 result = runner.invoke(app, ["Camila"])17 assert result.exit_code != 017- assert "Error: Missing option '--lastname'." in result.output18+ assert "Missing option '--lastname'." in result.output19 20 21 def test_option_lastname():22 result = runner.invoke(app, ["Camila", "--lastname", "Gutiérrez"])3 unmodified lines26 27 def test_help():28 result = runner.invoke(app, ["--help"])29 assert result.exit_code == 029- assert "--lastname TEXT" in result.output30+ assert "--lastname" in result.output31+ assert "TEXT" in result.output32 assert "[required]" in result.output33 34 35+def test_help_no_rich():36+ rich = typer.core.rich37+ typer.core.rich = None38+ result = runner.invoke(app, ["--help"])39+ assert result.exit_code == 040+ assert "--lastname" in result.output41+ assert "TEXT" in result.output42+ assert "[required]" in result.output43+ typer.core.rich = rich44+45+46 def test_script():47 result = subprocess.run(48 ["coverage", "run", mod.__file__, "--help"],49 stdout=subprocess.PIPE,4 unmodified linesmodified:tests/test_tutorial/test_options/test_version/test_tutorial003.py+1 added-1 removed
19 unmodified lines20 21 def test_2():22 result = runner.invoke(app, ["--name", "rick"])23 assert result.exit_code != 024- assert "Error: Invalid value for '--name': Only Camila is allowed" in result.output24+ assert "Invalid value for '--name': Only Camila is allowed" in result.output25 26 27 def test_3():28 result = runner.invoke(app, ["--name", "Camila"])29 unmodified linesmodified:tests/test_tutorial/test_parameter_types/test_bool/test_tutorial001.py+2 added-2 removed
34 unmodified lines35 assert result.exit_code != 036 # TODO: when deprecating Click 7, remove second option37 38 assert (39- "Error: No such option: --no-force" in result.output40- or "Error: no such option: --no-force" in result.output39+ "No such option: --no-force" in result.output40+ or "no such option: --no-force" in result.output41 )42 43 44 def test_script():7 unmodified linesmodified:tests/test_tutorial/test_parameter_types/test_bool/test_tutorial002.py+16 added-3 removed
1 import subprocess2 3 import typer4+import typer.core5 from typer.testing import CliRunner6 7 from docs_src.parameter_types.bool import tutorial002 as mod8 5 unmodified lines14 15 def test_help():16 result = runner.invoke(app, ["--help"])17 assert result.exit_code == 017- assert "--accept / --reject" in result.output18+ assert "--accept" in result.output19+ assert "--reject" in result.output20 assert "--no-accept" not in result.output21 22 23+def test_help_no_rich():24+ rich = typer.core.rich25+ typer.core.rich = None26+ result = runner.invoke(app, ["--help"])27+ assert result.exit_code == 028+ assert "--accept" in result.output29+ assert "--reject" in result.output30+ assert "--no-accept" not in result.output31+ typer.core.rich = rich32+33+34 def test_main():35 result = runner.invoke(app)36 assert result.exit_code == 037 assert "I don't know what you want yet" in result.output16 unmodified lines54 assert result.exit_code != 055 # TODO: when deprecating Click 7, remove second option56 57 assert (45- "Error: No such option: --no-accept" in result.output46- or "Error: no such option: --no-accept" in result.output58+ "No such option: --no-accept" in result.output59+ or "no such option: --no-accept" in result.output60 )61 62 63 def test_script():7 unmodified linesmodified:tests/test_tutorial/test_parameter_types/test_bool/test_tutorial003.py+4 added-1 removed
12 unmodified lines13 14 def test_help():15 result = runner.invoke(app, ["--help"])16 assert result.exit_code == 017- assert "-f, --force / -F, --no-force" in result.output17+ assert "-f" in result.output18+ assert "--force" in result.output19+ assert "-F" in result.output20+ assert "--no-force" in result.output21 22 23 def test_force():24 result = runner.invoke(app, ["-f"])18 unmodified linesmodified:tests/test_tutorial/test_parameter_types/test_bool/test_tutorial004.py+2 added-1 removed
12 unmodified lines13 14 def test_help():15 result = runner.invoke(app, ["--help"])16 assert result.exit_code == 017- assert "/ -d, --demo" in result.output17+ assert "-d" in result.output18+ assert "--demo" in result.output19 20 21 def test_main():22 result = runner.invoke(app)24 unmodified linesmodified:tests/test_tutorial/test_parameter_types/test_datetime/test_tutorial001.py+9 added-4 removed
25 unmodified lines26 27 def test_invalid():28 result = runner.invoke(app, ["july-19-1989"])29 assert result.exit_code != 030+ assert (31+ "Invalid value for 'BIRTH:[%Y-%m-%d|%Y-%m-%dT%H:%M:%S|%Y-%m-%d %H:%M:%S]':"32+ in result.stdout33+ )34 # TODO: when deprecating Click 7, remove second option35 assert (32- "Error: Invalid value for 'BIRTH:[%Y-%m-%d|%Y-%m-%dT%H:%M:%S|%Y-%m-%d %H:%M:%S]': 'july-19-1989' does not match the formats '%Y-%m-%d', '%Y-%m-%dT%H:%M:%S', '%Y-%m-%d %H:%M:%S'"33- in result.output34- or "Error: Invalid value for 'BIRTH:[%Y-%m-%d|%Y-%m-%dT%H:%M:%S|%Y-%m-%d %H:%M:%S]': invalid datetime format: july-19-1989. (choose from %Y-%m-%d, %Y-%m-%dT%H:%M:%S, %Y-%m-%d %H:%M:%S)"35- in result.output36+ "'july-19-1989' does not match the formats" in result.output37+ or "invalid datetime format: july-19-1989. (choose from" in result.output38 )39+ assert "%Y-%m-%d" in result.output40+ assert "%Y-%m-%dT%H:%M:%S" in result.output41+ assert "%Y-%m-%d %H:%M:%S" in result.output42 43 44 def test_script():45 result = subprocess.run(6 unmodified linesmodified:tests/test_tutorial/test_parameter_types/test_enum/test_tutorial001.py+7 added-4 removed
12 unmodified lines13 14 def test_help():15 result = runner.invoke(app, ["--help"])16 assert result.exit_code == 017- assert "--network [simple|conv|lstm]" in result.output17+ assert "--network" in result.output18+ assert "[simple|conv|lstm]" in result.output19 20 21 def test_main():22 result = runner.invoke(app, ["--network", "conv"])6 unmodified lines29 assert result.exit_code != 030 # TODO: when deprecating Click 7, remove second option31 32 assert (32- "Error: Invalid value for '--network': 'capsule' is not one of 'simple', 'conv', 'lstm'"33+ "Invalid value for '--network': 'capsule' is not one of" in result.output34+ or "Invalid value for '--network': invalid choice: capsule. (choose from"35 in result.output34- or "Error: Invalid value for '--network': invalid choice: capsule. (choose from simple, conv, lstm)"35- in result.output36 )37+ assert "simple" in result.output38+ assert "conv" in result.output39+ assert "lstm" in result.output40 41 42 def test_script():43 result = subprocess.run(6 unmodified linesmodified:tests/test_tutorial/test_parameter_types/test_index/test_tutorial001.py+6 added-6 removed
12 unmodified lines13 14 def test_help():15 result = runner.invoke(app, ["--help"])16 assert result.exit_code == 017- assert "--age INTEGER" in result.output18- assert "--height-meters FLOAT" in result.output17+ assert "--age" in result.output18+ assert "INTEGER" in result.output19+ assert "--height-meters" in result.output20+ assert "FLOAT" in result.output21 22 23 def test_params():24 result = runner.invoke(11 unmodified lines36 assert result.exit_code != 037 # TODO: when deprecating Click 7, remove second option38 39 assert (38- "Error: Invalid value for '--age': '15.3' is not a valid integer"39- in result.output40- or "Error: Invalid value for '--age': 15.3 is not a valid integer"41- in result.output40+ "Invalid value for '--age': '15.3' is not a valid integer" in result.output41+ or "Invalid value for '--age': 15.3 is not a valid integer" in result.output42 )43 44 45 def test_script():7 unmodified linesmodified:tests/test_tutorial/test_parameter_types/test_number/test_tutorial001.py+23 added-9 removed
1 import subprocess2 3 import typer4+import typer.core5 from typer.testing import CliRunner6 7 from docs_src.parameter_types.number import tutorial001 as mod8 5 unmodified lines14 15 def test_help():16 result = runner.invoke(app, ["--help"])17 assert result.exit_code == 017- assert "--age INTEGER RANGE" in result.output18- assert "--score FLOAT RANGE" in result.output18+ assert "--age" in result.output19+ assert "INTEGER RANGE" in result.output20+ assert "--score" in result.output21+ assert "FLOAT RANGE" in result.output22 23 24+def test_help_no_rich():25+ rich = typer.core.rich26+ typer.core.rich = None27+ result = runner.invoke(app, ["--help"])28+ assert result.exit_code == 029+ assert "--age" in result.output30+ assert "INTEGER RANGE" in result.output31+ assert "--score" in result.output32+ assert "FLOAT RANGE" in result.output33+ typer.core.rich = rich34+35+36 def test_params():37 result = runner.invoke(app, ["5", "--age", "20", "--score", "90"])38 assert result.exit_code == 039 assert "ID is 5" in result.output6 unmodified lines46 assert result.exit_code != 047 # TODO: when deprecating Click 7, remove second option48 assert (49 (35- "Error: Invalid value for 'ID': 1002 is not in the range 0<=x<=1000."50+ "Invalid value for 'ID': 1002 is not in the range 0<=x<=1000."51 in result.output52 )38- or "Error: Invalid value for 'ID': 1002 is not in the valid range of 0 to 1000."53+ or "Invalid value for 'ID': 1002 is not in the valid range of 0 to 1000."54 in result.output55 )56 57 2 unmodified lines60 assert result.exit_code != 061 # TODO: when deprecating Click 7, remove second option62 63 assert (49- "Error: Invalid value for '--age': 15 is not in the range x>=18"64+ "Invalid value for '--age': 15 is not in the range x>=18" in result.output65+ or "Invalid value for '--age': 15 is smaller than the minimum valid value 18."66 in result.output51- or "Error: Invalid value for '--age': 15 is smaller than the minimum valid value 18."52- in result.output67 )68 69 70 def test_invalid_score():1 unmodified line72 assert result.exit_code != 073 # TODO: when deprecating Click 7, remove second option74 75 assert (62- "Error: Invalid value for '--score': 100.5 is not in the range x<=100."76+ "Invalid value for '--score': 100.5 is not in the range x<=100."77 in result.output64- or "Error: Invalid value for '--score': 100.5 is bigger than the maximum valid value 100."78+ or "Invalid value for '--score': 100.5 is bigger than the maximum valid value"79 in result.output80 )81 82 16 unmodified linesmodified:tests/test_tutorial/test_parameter_types/test_number/test_tutorial002.py+2 added-3 removed
15 unmodified lines16 assert result.exit_code != 017 # TODO: when deprecating Click 7, remove second option18 19 assert (20- "Error: Invalid value for 'ID': 1002 is not in the range 0<=x<=1000"20+ "Invalid value for 'ID': 1002 is not in the range 0<=x<=1000" in result.output21+ or "Invalid value for 'ID': 1002 is not in the valid range of 0 to 1000."22 in result.output22- or "Error: Invalid value for 'ID': 1002 is not in the valid range of 0 to 1000."23- in result.output23 )24 25 26 def test_clamped():15 unmodified linesmodified:tests/test_tutorial/test_parameter_types/test_path/test_tutorial001.py+1 added-1 removed
15 unmodified lines16 Path(tmpdir) / "config.txt"17 result = runner.invoke(app)18 assert result.exit_code == 119 assert "No config file" in result.output20- assert "Aborted!" in result.output20+ assert "Aborted" in result.output21 22 23 def test_not_exists(tmpdir):24 config_file = Path(tmpdir) / "config.txt"30 unmodified linesmodified:tests/test_tutorial/test_parameter_types/test_path/test_tutorial002.py+2 added-5 removed
16 unmodified lines17 if config_file.exists(): # pragma no cover18 config_file.unlink()19 result = runner.invoke(app, ["--config", f"{config_file}"])20 assert result.exit_code != 021- assert "Error: Invalid value for '--config': File" in result.output21+ assert "Invalid value for '--config': File" in result.output22 assert "does not exist" in result.output23 24 25 def test_exists(tmpdir):7 unmodified lines33 34 def test_dir():35 result = runner.invoke(app, ["--config", "./"])36 assert result.exit_code != 037- assert (38- "Error: Invalid value for '--config': File './' is a directory."39- in result.output40- )37+ assert "Invalid value for '--config': File './' is a directory." in result.output38 39 40 def test_script():41 result = subprocess.run(6 unmodified linesmodified:tests/test_tutorial/test_parameter_types/test_uuid/test_tutorial001.py+2 added-2 removed
22 unmodified lines23 assert result.exit_code != 024 # TODO: when deprecating Click 7, remove second option25 26 assert (27- "Error: Invalid value for 'USER_ID': '7479706572-72756c6573' is not a valid UUID"27+ "Invalid value for 'USER_ID': '7479706572-72756c6573' is not a valid UUID"28 in result.output29- or "Error: Invalid value for 'USER_ID': 7479706572-72756c6573 is not a valid UUID value"29+ or "Invalid value for 'USER_ID': 7479706572-72756c6573 is not a valid UUID value"30 in result.output31 )32 33 8 unmodified linesmodified:tests/test_tutorial/test_prompt/test_tutorial002.py+1 added-1 removed
21 unmodified lines22 result = runner.invoke(app, input="n\n")23 assert result.exit_code == 124 assert "Are you sure you want to delete it? [y/N]:" in result.output25 assert "Not deleting" in result.output26- assert "Aborted!" in result.output26+ assert "Aborted" in result.output27 28 29 def test_script():30 result = subprocess.run(6 unmodified linesmodified:tests/test_tutorial/test_prompt/test_tutorial003.py+1 added-1 removed
20 unmodified lines21 def test_no_confirm():22 result = runner.invoke(app, input="n\n")23 assert result.exit_code == 124 assert "Are you sure you want to delete it? [y/N]:" in result.output25- assert "Aborted!" in result.output25+ assert "Aborted" in result.output26 27 28 def test_script():29 result = subprocess.run(6 unmodified linesmodified:tests/test_tutorial/test_subcommands/test_name_help/test_tutorial001.py+1 added-1 removed
10 unmodified lines11 12 def test_help():13 result = runner.invoke(app, ["--help"])14 assert result.exit_code == 015- assert "Commands:" in result.output15+ assert "Commands" in result.output16 assert "users" in result.output17 assert "Manage users in the app." in result.output18 19 20 unmodified linesmodified:tests/test_tutorial/test_subcommands/test_name_help/test_tutorial002.py+1 added-1 removed
10 unmodified lines11 12 def test_help():13 result = runner.invoke(app, ["--help"])14 assert result.exit_code == 015- assert "Commands:" in result.output15+ assert "Commands" in result.output16 assert "users" in result.output17 assert "Manage users in the app." in result.output18 19 20 unmodified linesmodified:tests/test_tutorial/test_subcommands/test_name_help/test_tutorial003.py+1 added-1 removed
10 unmodified lines11 12 def test_help():13 result = runner.invoke(app, ["--help"])14 assert result.exit_code == 015- assert "Commands:" in result.output15+ assert "Commands" in result.output16 assert "users" in result.output17 assert "Manage users in the app." in result.output18 19 20 unmodified linesmodified:tests/test_tutorial/test_subcommands/test_name_help/test_tutorial004.py+1 added-1 removed
10 unmodified lines11 12 def test_help():13 result = runner.invoke(app, ["--help"])14 assert result.exit_code == 015- assert "Commands:" in result.output15+ assert "Commands" in result.output16 assert "users" in result.output17 assert "Manage users in the app." in result.output18 19 20 unmodified linesmodified:tests/test_tutorial/test_subcommands/test_name_help/test_tutorial005.py+1 added-1 removed
10 unmodified lines11 12 def test_help():13 result = runner.invoke(app, ["--help"])14 assert result.exit_code == 015- assert "Commands:" in result.output15+ assert "Commands" in result.output16 assert "new-users" in result.output17 assert "I have the highland! Create some users." in result.output18 19 20 unmodified linesmodified:tests/test_tutorial/test_subcommands/test_name_help/test_tutorial006.py+1 added-1 removed
10 unmodified lines11 12 def test_help():13 result = runner.invoke(app, ["--help"])14 assert result.exit_code == 015- assert "Commands:" in result.output15+ assert "Commands" in result.output16 assert "exp-users" in result.output17 assert "Explicit help." in result.output18 19 20 unmodified linesmodified:tests/test_tutorial/test_subcommands/test_name_help/test_tutorial007.py+1 added-1 removed
10 unmodified lines11 12 def test_help():13 result = runner.invoke(app, ["--help"])14 assert result.exit_code == 015- assert "Commands:" in result.output15+ assert "Commands" in result.output16 assert "call-users" in result.output17 assert "Help from callback for users." in result.output18 19 20 unmodified linesmodified:tests/test_tutorial/test_subcommands/test_name_help/test_tutorial008.py+1 added-1 removed
10 unmodified lines11 12 def test_help():13 result = runner.invoke(app, ["--help"])14 assert result.exit_code == 015- assert "Commands:" in result.output15+ assert "Commands" in result.output16 assert "cake-sith-users" in result.output17 assert "Unlimited powder! Eh, users." in result.output18 19 20 unmodified linesmodified:tests/test_tutorial/test_subcommands/test_tutorial001.py+3 added-3 removed
24 unmodified lines25 def test_help(app):26 result = runner.invoke(app, ["--help"])27 assert result.exit_code == 028 assert "[OPTIONS] COMMAND [ARGS]..." in result.output29- assert "Commands:" in result.output29+ assert "Commands" in result.output30 assert "items" in result.output31 assert "users" in result.output32 33 34 def test_help_items(app):35 result = runner.invoke(app, ["items", "--help"])36 assert result.exit_code == 037 assert "[OPTIONS] COMMAND [ARGS]..." in result.output38- assert "Commands:" in result.output38+ assert "Commands" in result.output39 assert "create" in result.output40 assert "delete" in result.output41 assert "sell" in result.output42 19 unmodified lines62 def test_help_users(app):63 result = runner.invoke(app, ["users", "--help"])64 assert result.exit_code == 065 assert "[OPTIONS] COMMAND [ARGS]..." in result.output66- assert "Commands:" in result.output66+ assert "Commands" in result.output67 assert "create" in result.output68 assert "delete" in result.output69 assert "sell" not in result.output70 24 unmodified linesmodified:tests/test_tutorial/test_subcommands/test_tutorial002.py+3 added-3 removed
10 unmodified lines11 def test_help():12 result = runner.invoke(app, ["--help"])13 assert result.exit_code == 014 assert "[OPTIONS] COMMAND [ARGS]..." in result.output15- assert "Commands:" in result.output15+ assert "Commands" in result.output16 assert "items" in result.output17 assert "users" in result.output18 19 20 def test_help_items():21 result = runner.invoke(app, ["items", "--help"])22 assert result.exit_code == 023 assert "[OPTIONS] COMMAND [ARGS]..." in result.output24- assert "Commands:" in result.output24+ assert "Commands" in result.output25 assert "create" in result.output26 assert "delete" in result.output27 assert "sell" in result.output28 19 unmodified lines48 def test_help_users():49 result = runner.invoke(app, ["users", "--help"])50 assert result.exit_code == 051 assert "[OPTIONS] COMMAND [ARGS]..." in result.output52- assert "Commands:" in result.output52+ assert "Commands" in result.output53 assert "create" in result.output54 assert "delete" in result.output55 assert "sell" not in result.output56 21 unmodified linesmodified:tests/test_tutorial/test_subcommands/test_tutorial003.py+6 added-6 removed
24 unmodified lines25 def test_help(app):26 result = runner.invoke(app, ["--help"])27 assert result.exit_code == 028 assert "[OPTIONS] COMMAND [ARGS]..." in result.output29- assert "Commands:" in result.output29+ assert "Commands" in result.output30 assert "items" in result.output31 assert "users" in result.output32 assert "lands" in result.output33 1 unmodified line35 def test_help_items(app):36 result = runner.invoke(app, ["items", "--help"])37 assert result.exit_code == 038 assert "[OPTIONS] COMMAND [ARGS]..." in result.output39- assert "Commands:" in result.output39+ assert "Commands" in result.output40 assert "create" in result.output41 assert "delete" in result.output42 assert "sell" in result.output43 19 unmodified lines63 def test_help_users(app):64 result = runner.invoke(app, ["users", "--help"])65 assert result.exit_code == 066 assert "[OPTIONS] COMMAND [ARGS]..." in result.output67- assert "Commands:" in result.output67+ assert "Commands" in result.output68 assert "create" in result.output69 assert "delete" in result.output70 assert "sell" not in result.output71 13 unmodified lines85 def test_help_lands(app):86 result = runner.invoke(app, ["lands", "--help"])87 assert result.exit_code == 088 assert "lands [OPTIONS] COMMAND [ARGS]..." in result.output89- assert "Commands:" in result.output89+ assert "Commands" in result.output90 assert "reigns" in result.output91 assert "towns" in result.output92 93 94 def test_help_lands_reigns(app):95 result = runner.invoke(app, ["lands", "reigns", "--help"])96 assert result.exit_code == 097 assert "lands reigns [OPTIONS] COMMAND [ARGS]..." in result.output98- assert "Commands:" in result.output98+ assert "Commands" in result.output99 assert "conquer" in result.output100 assert "destroy" in result.output101 102 12 unmodified lines115 def test_help_lands_towns(app):116 result = runner.invoke(app, ["lands", "towns", "--help"])117 assert result.exit_code == 0118 assert "lands towns [OPTIONS] COMMAND [ARGS]..." in result.output119- assert "Commands:" in result.output119+ assert "Commands" in result.output120 assert "burn" in result.output121 assert "found" in result.output122 123 23 unmodified linesmodified:tests/test_tutorial/test_terminating/test_tutorial001.py+8 added
23 unmodified lines24 assert "The user already exists" in result.output25 assert "Notification sent for new user" not in result.output26 27 28+def test_existing_no_standalone():29+ # Mainly for coverage30+ result = runner.invoke(app, ["rick"], standalone_mode=False)31+ assert result.exit_code == 032+ assert "The user already exists" in result.output33+ assert "Notification sent for new user" not in result.output34+35+36 def test_script():37 result = subprocess.run(38 ["coverage", "run", mod.__file__, "--help"],39 stdout=subprocess.PIPE,4 unmodified linesmodified:tests/test_tutorial/test_terminating/test_tutorial003.py+19 added-1 removed
1 import subprocess2 3 import typer4+import typer.core5 from typer.testing import CliRunner6 7 from docs_src.terminating import tutorial003 as mod8 12 unmodified lines21 def test_root():22 result = runner.invoke(app, ["root"])23 assert result.exit_code == 124 assert "The root user is reserved" in result.output24- assert "Aborted!" in result.output25+ assert "Aborted" in result.output26 27 28+def test_root_no_standalone():29+ # Mainly for coverage30+ result = runner.invoke(app, ["root"], standalone_mode=False)31+ assert result.exit_code == 132+33+34+def test_root_no_rich():35+ # Mainly for coverage36+ rich = typer.core.rich37+ typer.core.rich = None38+ result = runner.invoke(app, ["root"])39+ assert result.exit_code == 140+ assert "The root user is reserved" in result.stdout41+ assert "Aborted!" in result.stdout42+ typer.core.rich = rich43+44+45 def test_script():46 result = subprocess.run(47 ["coverage", "run", mod.__file__, "--help"],48 stdout=subprocess.PIPE,4 unmodified linesmodified:tests/test_tutorial/test_using_click/test_tutorial003.py+1 added-1 removed
8 unmodified lines9 10 def test_cli():11 result = runner.invoke(mod.typer_click_object, [])12 # TODO: when deprecating Click 7, remove second option13- assert "Error: Missing command" in result.stdout or "Usage" in result.stdout13+ assert "Missing command" in result.stdout or "Usage" in result.stdout14 15 16 def test_typer():17 result = runner.invoke(mod.typer_click_object, ["top"])16 unmodified linesadded:tests/test_exit_errors.py+45 added
1+import errno2+3+import typer4+import typer.completion5+from typer.testing import CliRunner6+7+runner = CliRunner()8+9+10+def test_eoferror():11+ # Mainly for coverage/completeness12+ app = typer.Typer()13+14+ @app.command()15+ def main():16+ raise EOFError()17+18+ result = runner.invoke(app)19+ assert result.exit_code == 120+21+22+def test_oserror():23+ # Mainly for coverage/completeness24+ app = typer.Typer()25+26+ @app.command()27+ def main():28+ e = OSError()29+ e.errno = errno.EPIPE30+ raise e31+32+ result = runner.invoke(app)33+ assert result.exit_code == 134+35+36+def test_oserror_no_epipe():37+ # Mainly for coverage/completeness38+ app = typer.Typer()39+40+ @app.command()41+ def main():42+ raise OSError()43+44+ result = runner.invoke(app)45+ assert result.exit_code == 1modified:tests/test_others.py+15 added-17 removed
30 unmodified lines31 app = typer.Typer()32 33 @app.command()34 def main():35- typer.echo("Hello World")35+ print("Hello World")36 37 with mock.patch.object(38 shellingham, "detect_shell", return_value=("xshell", "/usr/bin/xshell")39 ):23 unmodified lines63 def test_callback_2_untyped_parameters():64 app = typer.Typer()65 66 def name_callback(ctx, value):67- typer.echo(f"info name is: {ctx.info_name}")68- typer.echo(f"value is: {value}")67+ print(f"info name is: {ctx.info_name}")68+ print(f"value is: {value}")69 70 @app.command()71 def main(name: str = typer.Option(..., callback=name_callback)):72- typer.echo("Hello World")72+ print("Hello World")73 74 result = runner.invoke(app, ["--name", "Camila"])75 assert "info name is: main" in result.stdout76 assert "value is: Camila" in result.stdout2 unmodified lines79 def test_callback_3_untyped_parameters():80 app = typer.Typer()81 82 def name_callback(ctx, param, value):83- typer.echo(f"info name is: {ctx.info_name}")84- typer.echo(f"param name is: {param.name}")85- typer.echo(f"value is: {value}")83+ print(f"info name is: {ctx.info_name}")84+ print(f"param name is: {param.name}")85+ print(f"value is: {value}")86 87 @app.command()88 def main(name: str = typer.Option(..., callback=name_callback)):89- typer.echo("Hello World")89+ print("Hello World")90 91 result = runner.invoke(app, ["--name", "Camila"])92 assert "info name is: main" in result.stdout93 assert "param name is: name" in result.stdout85 unmodified lines179 app = typer.Typer()180 181 @app.command()182 def main(arg1, arg2: int, arg3: "int", arg4: bool = False, arg5: "bool" = False):183- typer.echo(f"arg1: {type(arg1)} {arg1}")184- typer.echo(f"arg2: {type(arg2)} {arg2}")185- typer.echo(f"arg3: {type(arg3)} {arg3}")186- typer.echo(f"arg4: {type(arg4)} {arg4}")187- typer.echo(f"arg5: {type(arg5)} {arg5}")183+ print(f"arg1: {type(arg1)} {arg1}")184+ print(f"arg2: {type(arg2)} {arg2}")185+ print(f"arg3: {type(arg3)} {arg3}")186+ print(f"arg4: {type(arg4)} {arg4}")187+ print(f"arg5: {type(arg5)} {arg5}")188 189 result = runner.invoke(app, ["Hello", "2", "invalid"])190 # TODO: when deprecating Click 7, remove second option191 192 assert (193- "Error: Invalid value for 'ARG3': 'invalid' is not a valid integer"194- in result.stdout195- or "Error: Invalid value for 'ARG3': invalid is not a valid integer"196- in result.stdout193+ "Invalid value for 'ARG3': 'invalid' is not a valid integer" in result.stdout194+ or "Invalid value for 'ARG3': invalid is not a valid integer" in result.stdout195 )196 result = runner.invoke(app, ["Hello", "2", "3", "--arg4", "--arg5"])197 assert (198 "arg1: <class 'str'> Hello\narg2: <class 'int'> 2\narg3: <class 'int'> 3\narg4: <class 'bool'> True\narg5: <class 'bool'> True\n"13 unmodified linesadded:tests/test_rich_utils.py+38 added
1+import typer2+import typer.completion3+from typer.testing import CliRunner4+5+runner = CliRunner()6+7+8+def test_rich_utils_click_rewrapp():9+ app = typer.Typer(rich_markup_mode="markdown")10+11+ @app.command()12+ def main():13+ """14+ \b15+ Some text16+17+ Some unwrapped text18+ """19+ print("Hello World")20+21+ @app.command()22+ def secondary():23+ """24+ \b25+ Secondary text26+27+ Some unwrapped text28+ """29+ print("Hello Secondary World")30+31+ result = runner.invoke(app, ["--help"])32+ assert "Some text" in result.stdout33+ assert "Secondary text" in result.stdout34+ assert "\b" not in result.stdout35+ result = runner.invoke(app, ["main"])36+ assert "Hello World" in result.stdout37+ result = runner.invoke(app, ["secondary"])38+ assert "Hello Secondary World" in result.stdoutmodified:tests/test_tracebacks.py+29 added
1+import os2 import subprocess3 from pathlib import Path4 5 3 unmodified lines9 ["coverage", "run", str(file_path)],10 stdout=subprocess.PIPE,11 stderr=subprocess.PIPE,12 encoding="utf-8",13+ env={**os.environ, "_TYPER_STANDARD_TRACEBACK": ""},14 )15 assert "return get_command(self)(*args, **kwargs)" not in result.stderr16 17 assert "typer.run(main)" not in result.stderr6 unmodified lines24 )25 assert "name = 'morty'" in result.stderr26 27 28+def test_standard_traceback_env_var():29+ file_path = Path(__file__).parent / "assets/type_error_rich.py"30+ result = subprocess.run(31+ ["coverage", "run", str(file_path)],32+ stdout=subprocess.PIPE,33+ stderr=subprocess.PIPE,34+ encoding="utf-8",35+ env={**os.environ, "_TYPER_STANDARD_TRACEBACK": "1"},36+ )37+ assert "return get_command(self)(*args, **kwargs)" in result.stderr38+39+ assert "typer.run(main)" in result.stderr40+ assert "print(name + 3)" in result.stderr41+42+ # TODO: when deprecating Python 3.6, remove second option43+ assert (44+ 'TypeError: can only concatenate str (not "int") to str' in result.stderr45+ or "TypeError: must be str, not int" in result.stderr46+ )47+ assert "name = 'morty'" not in result.stderr48+49+50 def test_traceback_rich_pretty_short_disable():51 file_path = Path(__file__).parent / "assets/type_error_rich_short_disable.py"52 result = subprocess.run(53 ["coverage", "run", str(file_path)],54 stdout=subprocess.PIPE,55 stderr=subprocess.PIPE,56 encoding="utf-8",57+ env={**os.environ, "_TYPER_STANDARD_TRACEBACK": ""},58 )59 assert "return get_command(self)(*args, **kwargs)" not in result.stderr60 61 assert "app()" in result.stderr13 unmodified lines75 ["coverage", "run", str(file_path)],76 stdout=subprocess.PIPE,77 stderr=subprocess.PIPE,78 encoding="utf-8",79+ env={**os.environ, "_TYPER_STANDARD_TRACEBACK": ""},80 )81 assert "return get_command(self)(*args, **kwargs)" not in result.stderr82 83 assert "typer.run(main)" in result.stderr11 unmodified lines95 ["coverage", "run", str(file_path)],96 stdout=subprocess.PIPE,97 stderr=subprocess.PIPE,98 encoding="utf-8",99+ env={**os.environ, "_TYPER_STANDARD_TRACEBACK": ""},100 )101 assert "return get_command(self)(*args, **kwargs)" not in result.stderr102 103 assert "app()" in result.stderr11 unmodified lines115 ["coverage", "run", str(file_path)],116 stdout=subprocess.PIPE,117 stderr=subprocess.PIPE,118 encoding="utf-8",119+ env={**os.environ, "_TYPER_STANDARD_TRACEBACK": ""},120 )121 assert "morty" in result.stdout, "the call to the first app should work normally"122 assert "return callback(**use_params)" in result.stderr, (123 "calling outside of Typer should show the normal traceback, "14 unmodified lines138 ["coverage", "run", str(file_path)],139 stdout=subprocess.PIPE,140 stderr=subprocess.PIPE,141 encoding="utf-8",142+ env={**os.environ, "_TYPER_STANDARD_TRACEBACK": ""},143 )144 assert "return get_command(self)(*args, **kwargs)" in result.stderr145 146 assert "app()" in result.stderr6 unmodified linesmodified:tests/test_type_conversion.py+3 added-3 removed
13 unmodified lines14 15 @app.command()16 def opt(user: Optional[str] = None):17 if user:18- typer.echo(f"User: {user}")18+ print(f"User: {user}")19 else:20- typer.echo("No user")20+ print("No user")21 22 result = runner.invoke(app)23 assert result.exit_code == 024 assert "No user" in result.output7 unmodified lines32 app = typer.Typer()33 34 @app.command()35 def no_type(user):36- typer.echo(f"User: {user}")36+ print(f"User: {user}")37 38 result = runner.invoke(app, ["Camila"])39 assert result.exit_code == 040 assert "User: Camila" in result.output52 unmodified linesadded:typer/_compat_utils.py+5 added
1+import click2+3+4+def _get_click_major() -> int:5+ return int(click.__version__.split(".")[0])modified:typer/completion.py+2 added-1 removed
2 unmodified lines3 from typing import Any, Dict, Tuple4 5 import click6 7+from ._compat_utils import _get_click_major8 from ._completion_shared import Shells, get_completion_script, install9 from .models import ParamMeta10 from .params import Option10-from .utils import _get_click_major, get_params_from_function11+from .utils import get_params_from_function12 13 try:14 import shellingham15 except ImportError: # pragma: nocover145 unmodified linesmodified:typer/core.py+373 added-48 removed
1+import errno2 import inspect3 import os4 import sys5 from gettext import gettext as _4 unmodified lines10 Dict,11 List,12 Optional,13 Sequence,14+ TextIO,15 Tuple,16 Union,17 cast,18 )2 unmodified lines21 import click.core22 import click.formatting23 import click.parser24 import click.types25+import click.utils26+from typer.completion import completion_init27 24-from .utils import _get_click_major28+from ._compat_utils import _get_click_major29 30+if sys.version_info >= (3, 8):31+ from typing import Literal32+else:33+ from typing_extensions import Literal34+35+try:36+ import rich37+38+ from . import rich_utils39+40+except ImportError: # pragma: nocover41+ rich = None # type: ignore42+43 if TYPE_CHECKING: # pragma: no cover44+ if _get_click_major() == 7:27- import click.shell_completion45+ import click.shell_completion46 47+MarkupMode = Literal["markdown", "rich", None]48 49+50 # TODO: when deprecating Click 7, remove this51 def _typer_param_shell_complete(52 self: click.core.Parameter, ctx: click.Context, incomplete: str53 ) -> List["click.shell_completion.CompletionItem"]:48 unmodified lines102 103 self._custom_shell_complete = compat_autocompletion104 105 106+def _get_default_string(107+ obj: Union["TyperArgument", "TyperOption"],108+ *,109+ ctx: click.Context,110+ show_default_is_str: bool,111+ default_value: Union[List[Any], Tuple[Any, ...], str, Callable[..., Any], Any],112+) -> str:113+ # Extracted from click.core.Option.get_help_record() to be reused by114+ # rich_utils avoiding RegEx hacks115+ if show_default_is_str:116+ default_string = f"({obj.show_default})"117+ elif isinstance(default_value, (list, tuple)):118+ default_string = ", ".join(str(d) for d in default_value)119+ elif callable(default_value):120+ default_string = _("(dynamic)")121+ elif isinstance(obj, TyperOption) and obj.is_bool_flag and obj.secondary_opts:122+ # For boolean flags that have distinct True/False opts,123+ # use the opt without prefix instead of the value.124+ # Typer override, original commented125+ # default_string = click.parser.split_opt(126+ # (self.opts if self.default else self.secondary_opts)[0]127+ # )[1]128+ if obj.default:129+ if obj.opts:130+ default_string = click.parser.split_opt(obj.opts[0])[1]131+ else:132+ default_string = str(default_value)133+ else:134+ default_string = click.parser.split_opt(obj.secondary_opts[0])[1]135+ # Typer override end136+ elif (137+ isinstance(obj, TyperOption)138+ and obj.is_bool_flag139+ and not obj.secondary_opts140+ and not default_value141+ ):142+ default_string = ""143+ else:144+ default_string = str(default_value)145+ return default_string146+147+148+def _extract_default_help_str(149+ obj: Union["TyperArgument", "TyperOption"], *, ctx: click.Context150+) -> Optional[Union[Any, Callable[[], Any]]]:151+ # Extracted from click.core.Option.get_help_record() to be reused by152+ # rich_utils avoiding RegEx hacks153+ # Temporarily enable resilient parsing to avoid type casting154+ # failing for the default. Might be possible to extend this to155+ # help formatting in general.156+ resilient = ctx.resilient_parsing157+ ctx.resilient_parsing = True158+159+ try:160+ if _get_click_major() > 7:161+ default_value = obj.get_default(ctx, call=False)162+ else:163+ if inspect.isfunction(obj.default):164+ default_value = "(dynamic)"165+ else:166+ default_value = obj.default167+ finally:168+ ctx.resilient_parsing = resilient169+ return default_value170+171+172+def _main(173+ self: click.Command,174+ *,175+ args: Optional[Sequence[str]] = None,176+ prog_name: Optional[str] = None,177+ complete_var: Optional[str] = None,178+ standalone_mode: bool = True,179+ windows_expand_args: bool = True,180+ **extra: Any,181+) -> Any:182+ # Typer override, duplicated from click.main() to handle custom rich exceptions183+ # Verify that the environment is configured correctly, or reject184+ # further execution to avoid a broken script.185+ if args is None:186+ args = sys.argv[1:]187+188+ # Covered in Click tests189+ if os.name == "nt" and windows_expand_args: # pragma: no cover190+ args = click.utils._expand_args(args)191+ else:192+ args = list(args)193+194+ if prog_name is None:195+ if _get_click_major() > 7:196+ prog_name = click.utils._detect_program_name()197+ else:198+ from click.utils import make_str199+200+ prog_name = make_str(201+ os.path.basename(sys.argv[0] if sys.argv else __file__)202+ )203+204+ # Process shell completion requests and exit early.205+ if _get_click_major() > 7:206+ self._main_shell_completion(extra, prog_name, complete_var)207+ else:208+ completion_init()209+ from click.core import _bashcomplete # type: ignore210+211+ _bashcomplete(self, prog_name, complete_var)212+213+ try:214+ try:215+ with self.make_context(prog_name, args, **extra) as ctx:216+ rv = self.invoke(ctx)217+ if not standalone_mode:218+ return rv219+ # it's not safe to `ctx.exit(rv)` here!220+ # note that `rv` may actually contain data like "1" which221+ # has obvious effects222+ # more subtle case: `rv=[None, None]` can come out of223+ # chained commands which all returned `None` -- so it's not224+ # even always obvious that `rv` indicates success/failure225+ # by its truthiness/falsiness226+ ctx.exit()227+ except (EOFError, KeyboardInterrupt):228+ click.echo(file=sys.stderr)229+ raise click.Abort()230+ except click.ClickException as e:231+ if not standalone_mode:232+ raise233+ # Typer override234+ if rich:235+ rich_utils.rich_format_error(e)236+ else:237+ e.show()238+ # Typer override end239+ sys.exit(e.exit_code)240+ except OSError as e:241+ if e.errno == errno.EPIPE:242+ sys.stdout = cast(TextIO, click.utils.PacifyFlushWrapper(sys.stdout))243+ sys.stderr = cast(TextIO, click.utils.PacifyFlushWrapper(sys.stderr))244+ sys.exit(1)245+ else:246+ raise247+ except click.exceptions.Exit as e:248+ if standalone_mode:249+ sys.exit(e.exit_code)250+ else:251+ # in non-standalone mode, return the exit code252+ # note that this is only reached if `self.invoke` above raises253+ # an Exit explicitly -- thus bypassing the check there which254+ # would return its result255+ # the results of non-standalone execution may therefore be256+ # somewhat ambiguous: if there are codepaths which lead to257+ # `ctx.exit(1)` and to `return 1`, the caller won't be able to258+ # tell the difference between the two259+ return e.exit_code260+ except click.Abort:261+ if not standalone_mode:262+ raise263+ # Typer override264+ if rich:265+ rich_utils.rich_abort_error()266+ else:267+ click.echo(_("Aborted!"), file=sys.stderr)268+ # Typer override end269+ sys.exit(1)270+271+272 class TyperArgument(click.core.Argument):273 def __init__(274 self,275 *,20 unmodified lines296 show_choices: bool = True,297 show_envvar: bool = True,298 help: Optional[str] = None,299 hidden: bool = False,300+ # Rich settings301+ rich_help_panel: Union[str, None] = None,302 ):303 self.help = help304 self.show_default = show_default305 self.show_choices = show_choices306 self.show_envvar = show_envvar307 self.hidden = hidden308+ self.rich_help_panel = rich_help_panel309 kwargs: Dict[str, Any] = {310 "param_decls": param_decls,311 "type": type,312 "required": required,14 unmodified lines327 _typer_param_setup_autocompletion_compat(328 self, autocompletion=autocompletion329 )330 331+ def _get_default_string(332+ self,333+ *,334+ ctx: click.Context,335+ show_default_is_str: bool,336+ default_value: Union[List[Any], Tuple[Any, ...], str, Callable[..., Any], Any],337+ ) -> str:338+ return _get_default_string(339+ self,340+ ctx=ctx,341+ show_default_is_str=show_default_is_str,342+ default_value=default_value,343+ )344+345+ def _extract_default_help_str(346+ self, *, ctx: click.Context347+ ) -> Optional[Union[Any, Callable[[], Any]]]:348+ return _extract_default_help_str(self, ctx=ctx)349+350 def get_help_record(self, ctx: click.Context) -> Optional[Tuple[str, str]]:351 # Modified version of click.core.Option.get_help_record()352 # to support Arguments353 if self.hidden:10 unmodified lines364 if isinstance(envvar, (list, tuple))365 else envvar366 )367 extra.append(f"env var: {var_str}")160- if self.default is not None and (self.show_default or ctx.show_default):161- if isinstance(self.show_default, str):162- default_string = f"({self.show_default})"163- elif isinstance(self.default, (list, tuple)):164- default_string = ", ".join(str(d) for d in self.default)165- elif inspect.isfunction(self.default):166- default_string = "(dynamic)"167- else:168- default_string = str(self.default)169- extra.append(f"default: {default_string}")368+369+ # Typer override:370+ # Extracted to _extract_default_help_str() to allow re-using it in rich_utils371+ default_value = self._extract_default_help_str(ctx=ctx)372+ # Typer override end373+374+ show_default_is_str = isinstance(self.show_default, str)375+376+ if show_default_is_str or (377+ default_value is not None and (self.show_default or ctx.show_default)378+ ):379+ # Typer override:380+ # Extracted to _get_default_string() to allow re-using it in rich_utils381+ default_string = self._get_default_string(382+ ctx=ctx,383+ show_default_is_str=show_default_is_str,384+ default_value=default_value,385+ )386+ # Typer override end387+ if default_string:388+ extra.append(_("default: {default}").format(default=default_string))389 if self.required:390 extra.append("required")391 if extra:392 extra_str = ";".join(extra)57 unmodified lines450 help: Optional[str] = None,451 hidden: bool = False,452 show_choices: bool = True,453 show_envvar: bool = False,454+ # Rich settings455+ rich_help_panel: Union[str, None] = None,456 ):457 # TODO: when deprecating Click 7, remove custom kwargs with prompt_required458 # and call super().__init__() directly459 kwargs: Dict[str, Any] = {30 unmodified lines490 if _get_click_major() > 7:491 _typer_param_setup_autocompletion_compat(492 self, autocompletion=autocompletion493 )494+ self.rich_help_panel = rich_help_panel495 496+ def _get_default_string(497+ self,498+ *,499+ ctx: click.Context,500+ show_default_is_str: bool,501+ default_value: Union[List[Any], Tuple[Any, ...], str, Callable[..., Any], Any],502+ ) -> str:503+ return _get_default_string(504+ self,505+ ctx=ctx,506+ show_default_is_str=show_default_is_str,507+ default_value=default_value,508+ )509+510+ def _extract_default_help_str(511+ self, *, ctx: click.Context512+ ) -> Optional[Union[Any, Callable[[], Any]]]:513+ return _extract_default_help_str(self, ctx=ctx)514+515 def get_help_record(self, ctx: click.Context) -> Optional[Tuple[str, str]]:516 # Click 7.x was not breaking this use case, so in that case, re-use its logic517 if _get_click_major() < 8:518 return super().get_help_record(ctx)44 unmodified lines563 else ", ".join(str(d) for d in envvar)564 )565 extra.append(_("env var: {var}").format(var=var_str))566 326- # Temporarily enable resilient parsing to avoid type casting327- # failing for the default. Might be possible to extend this to328- # help formatting in general.329- resilient = ctx.resilient_parsing330- ctx.resilient_parsing = True567+ # Typer override:568+ # Extracted to _extract_default() to allow re-using it in rich_utils569+ default_value = self._extract_default_help_str(ctx=ctx)570+ # Typer override end571 332- try:333- default_value = self.get_default(ctx, call=False)334- finally:335- ctx.resilient_parsing = resilient336-572 show_default_is_str = isinstance(self.show_default, str)573 574 if show_default_is_str or (575 default_value is not None and (self.show_default or ctx.show_default)576 ):342- if show_default_is_str:343- default_string = f"({self.show_default})"344- elif isinstance(default_value, (list, tuple)):345- default_string = ", ".join(str(d) for d in default_value)346- elif callable(default_value):347- default_string = _("(dynamic)")348- elif self.is_bool_flag and self.secondary_opts:349- # For boolean flags that have distinct True/False opts,350- # use the opt without prefix instead of the value.351- # Typer override, original commented352- # default_string = click.parser.split_opt(353- # (self.opts if self.default else self.secondary_opts)[0]354- # )[1]355- if self.default:356- if self.opts:357- default_string = click.parser.split_opt(self.opts[0])[1]358- else:359- default_string = str(default_value)360- else:361- default_string = click.parser.split_opt(self.secondary_opts[0])[1]362- # Typer override end363- elif self.is_bool_flag and not self.secondary_opts and not default_value:364- default_string = ""365- else:366- default_string = str(default_value)367-577+ # Typer override:578+ # Extracted to _get_default_string() to allow re-using it in rich_utils579+ default_string = self._get_default_string(580+ ctx=ctx,581+ show_default_is_str=show_default_is_str,582+ default_value=default_value,583+ )584+ # Typer override end585 if default_string:586 extra.append(_("default: {default}").format(default=default_string))587 588 if isinstance(self.type, click.types._NumberRangeBase):63 unmodified lines652 sys.exit(rv)653 654 655 class TyperCommand(click.core.Command):656+ def __init__(657+ self,658+ name: Optional[str],659+ *,660+ context_settings: Optional[Dict[str, Any]] = None,661+ callback: Optional[Callable[..., Any]] = None,662+ params: Optional[List[click.Parameter]] = None,663+ help: Optional[str] = None,664+ epilog: Optional[str] = None,665+ short_help: Optional[str] = None,666+ options_metavar: Optional[str] = "[OPTIONS]",667+ add_help_option: bool = True,668+ no_args_is_help: bool = False,669+ hidden: bool = False,670+ deprecated: bool = False,671+ # Rich settings672+ rich_markup_mode: MarkupMode = None,673+ rich_help_panel: Union[str, None] = None,674+ ) -> None:675+ super().__init__(676+ name=name,677+ context_settings=context_settings,678+ callback=callback,679+ params=params,680+ help=help,681+ epilog=epilog,682+ short_help=short_help,683+ options_metavar=options_metavar,684+ add_help_option=add_help_option,685+ no_args_is_help=no_args_is_help,686+ hidden=hidden,687+ deprecated=deprecated,688+ )689+ self.rich_markup_mode: MarkupMode = rich_markup_mode690+ self.rich_help_panel = rich_help_panel691+692 def format_options(693 self, ctx: click.Context, formatter: click.HelpFormatter694 ) -> None:695 _typer_format_options(self, ctx=ctx, formatter=formatter)7 unmodified lines703 _typer_main_shell_completion(704 self, ctx_args=ctx_args, prog_name=prog_name, complete_var=complete_var705 )706 707+ def main(708+ self,709+ args: Optional[Sequence[str]] = None,710+ prog_name: Optional[str] = None,711+ complete_var: Optional[str] = None,712+ standalone_mode: bool = True,713+ windows_expand_args: bool = True,714+ **extra: Any,715+ ) -> Any:716+ return _main(717+ self,718+ args=args,719+ prog_name=prog_name,720+ complete_var=complete_var,721+ standalone_mode=standalone_mode,722+ windows_expand_args=windows_expand_args,723+ **extra,724+ )725 726+ def format_help(self, ctx: click.Context, formatter: click.HelpFormatter) -> None:727+ if not rich:728+ return super().format_help(ctx, formatter)729+ return rich_utils.rich_format_help(730+ obj=self,731+ ctx=ctx,732+ markup_mode=self.rich_markup_mode,733+ )734+735+736 class TyperGroup(click.core.Group):737+ def __init__(738+ self,739+ *,740+ name: Optional[str] = None,741+ commands: Optional[742+ Union[Dict[str, click.Command], Sequence[click.Command]]743+ ] = None,744+ # Rich settings745+ rich_markup_mode: MarkupMode = None,746+ rich_help_panel: Union[str, None] = None,747+ **attrs: Any,748+ ) -> None:749+ super().__init__(name=name, commands=commands, **attrs)750+ self.rich_markup_mode: MarkupMode = rich_markup_mode751+ self.rich_help_panel = rich_help_panel752+753 def format_options(754 self, ctx: click.Context, formatter: click.HelpFormatter755 ) -> None:756 _typer_format_options(self, ctx=ctx, formatter=formatter)7 unmodified lines764 ) -> None:765 _typer_main_shell_completion(766 self, ctx_args=ctx_args, prog_name=prog_name, complete_var=complete_var767 )768+769+ def main(770+ self,771+ args: Optional[Sequence[str]] = None,772+ prog_name: Optional[str] = None,773+ complete_var: Optional[str] = None,774+ standalone_mode: bool = True,775+ windows_expand_args: bool = True,776+ **extra: Any,777+ ) -> Any:778+ return _main(779+ self,780+ args=args,781+ prog_name=prog_name,782+ complete_var=complete_var,783+ standalone_mode=standalone_mode,784+ windows_expand_args=windows_expand_args,785+ **extra,786+ )787+788+ def format_help(self, ctx: click.Context, formatter: click.HelpFormatter) -> None:789+ if not rich:790+ return super().format_help(ctx, formatter)791+ return rich_utils.rich_format_help(792+ obj=self,793+ ctx=ctx,794+ markup_mode=self.rich_markup_mode,795+ )modified:typer/main.py+57 added-13 removed
12 unmodified lines13 14 import click15 16 from .completion import get_completion_inspect_parameters17-from .core import TyperArgument, TyperCommand, TyperGroup, TyperOption17+from .core import MarkupMode, TyperArgument, TyperCommand, TyperGroup, TyperOption18 from .models import (19 AnyType,20 ArgumentInfo,21 CommandFunctionType,33 unmodified lines55 ) -> None:56 exception_config: Union[DeveloperExceptionConfig, None] = getattr(57 exc_value, _typer_developer_exception_attr_name, None58 )59- if not exception_config or not exception_config.pretty_errors_enable:59+ standard_traceback = os.getenv("_TYPER_STANDARD_TRACEBACK")60+ if (61+ standard_traceback62+ or not exception_config63+ or not exception_config.pretty_errors_enable64+ ):65 _original_except_hook(exc_type, exc_value, tb)66 return67 typer_path = os.path.dirname(__file__)68 click_path = os.path.dirname(click.__file__)46 unmodified lines115 def __init__(116 self,117 *,118 name: Optional[str] = Default(None),114- cls: Optional[Type[click.Command]] = Default(None),119+ cls: Optional[Type[TyperGroup]] = Default(None),120 invoke_without_command: bool = Default(False),121 no_args_is_help: bool = Default(False),122 subcommand_metavar: Optional[str] = Default(None),123 chain: bool = Default(False),8 unmodified lines132 add_help_option: bool = Default(True),133 hidden: bool = Default(False),134 deprecated: bool = Default(False),135 add_completion: bool = True,136+ # Rich settings137+ rich_markup_mode: MarkupMode = None,138+ rich_help_panel: Union[str, None] = Default(None),139 pretty_errors_enable: bool = True,140 pretty_errors_show_locals: bool = True,141 pretty_errors_short: bool = True,142 ):143 self._add_completion = add_completion144+ self.rich_markup_mode: MarkupMode = rich_markup_mode145+ self.rich_help_panel = rich_help_panel146 self.pretty_errors_enable = pretty_errors_enable147 self.pretty_errors_show_locals = pretty_errors_show_locals148 self.pretty_errors_short = pretty_errors_short149 self.info = TyperInfo(21 unmodified lines171 def callback(172 self,173 name: Optional[str] = Default(None),174 *,165- cls: Optional[Type[click.Command]] = Default(None),175+ cls: Optional[Type[TyperGroup]] = Default(None),176 invoke_without_command: bool = Default(False),177 no_args_is_help: bool = Default(False),178 subcommand_metavar: Optional[str] = Default(None),179 chain: bool = Default(False),6 unmodified lines186 options_metavar: str = Default("[OPTIONS]"),187 add_help_option: bool = Default(True),188 hidden: bool = Default(False),189 deprecated: bool = Default(False),190+ # Rich settings191+ rich_help_panel: Union[str, None] = Default(None),192 ) -> Callable[[CommandFunctionType], CommandFunctionType]:193 def decorator(f: CommandFunctionType) -> CommandFunctionType:194 self.registered_callback = TyperInfo(195 name=name,11 unmodified lines207 options_metavar=options_metavar,208 add_help_option=add_help_option,209 hidden=hidden,210 deprecated=deprecated,211+ rich_help_panel=rich_help_panel,212 )213 return f214 215 return decorator1 unmodified line217 def command(218 self,219 name: Optional[str] = None,220 *,208- cls: Optional[Type[click.Command]] = None,221+ cls: Optional[Type[TyperCommand]] = None,222 context_settings: Optional[Dict[Any, Any]] = None,223 help: Optional[str] = None,224 epilog: Optional[str] = None,225 short_help: Optional[str] = None,1 unmodified line227 add_help_option: bool = True,228 no_args_is_help: bool = False,229 hidden: bool = False,230 deprecated: bool = False,231+ # Rich settings232+ rich_help_panel: Union[str, None] = Default(None),233 ) -> Callable[[CommandFunctionType], CommandFunctionType]:234 if cls is None:235 cls = TyperCommand236 11 unmodified lines248 add_help_option=add_help_option,249 no_args_is_help=no_args_is_help,250 hidden=hidden,251 deprecated=deprecated,252+ # Rich settings253+ rich_help_panel=rich_help_panel,254 )255 )256 return f257 3 unmodified lines261 self,262 typer_instance: "Typer",263 *,264 name: Optional[str] = Default(None),248- cls: Optional[Type[click.Command]] = Default(None),265+ cls: Optional[Type[TyperGroup]] = Default(None),266 invoke_without_command: bool = Default(False),267 no_args_is_help: bool = Default(False),268 subcommand_metavar: Optional[str] = Default(None),269 chain: bool = Default(False),7 unmodified lines277 options_metavar: str = Default("[OPTIONS]"),278 add_help_option: bool = Default(True),279 hidden: bool = Default(False),280 deprecated: bool = Default(False),281+ # Rich settings282+ rich_help_panel: Union[str, None] = Default(None),283 ) -> None:284 self.registered_groups.append(285 TyperInfo(286 typer_instance,12 unmodified lines299 options_metavar=options_metavar,300 add_help_option=add_help_option,301 hidden=hidden,302 deprecated=deprecated,303+ rich_help_panel=rich_help_panel,304 )305 )306 307 def __call__(self, *args: Any, **kwargs: Any) -> Any:23 unmodified lines331 def get_group(typer_instance: Typer) -> click.Command:332 group = get_group_from_info(333 TyperInfo(typer_instance),334 pretty_errors_short=typer_instance.pretty_errors_short,335+ rich_markup_mode=typer_instance.rich_markup_mode,336 )337 return group338 339 21 unmodified lines361 ):362 single_command.context_settings = typer_instance.info.context_settings363 364 click_command = get_command_from_info(344- single_command, pretty_errors_short=typer_instance.pretty_errors_short365+ single_command,366+ pretty_errors_short=typer_instance.pretty_errors_short,367+ rich_markup_mode=typer_instance.rich_markup_mode,368 )369 if typer_instance._add_completion:370 click_command.params.append(click_install_param)371 click_command.params.append(click_show_param)97 unmodified lines469 return TyperInfo(**values)470 471 472 def get_group_from_info(450- group_info: TyperInfo, *, pretty_errors_short: bool473+ group_info: TyperInfo,474+ *,475+ pretty_errors_short: bool,476+ rich_markup_mode: MarkupMode,477 ) -> click.Command:478 assert (479 group_info.typer_instance480 ), "A Typer instance is needed to generate a Click Group"481 commands: Dict[str, click.Command] = {}482 for command_info in group_info.typer_instance.registered_commands:483 command = get_command_from_info(458- command_info=command_info, pretty_errors_short=pretty_errors_short484+ command_info=command_info,485+ pretty_errors_short=pretty_errors_short,486+ rich_markup_mode=rich_markup_mode,487 )488 if command.name:489 commands[command.name] = command490 for sub_group_info in group_info.typer_instance.registered_groups:491 sub_group = get_group_from_info(464- sub_group_info, pretty_errors_short=pretty_errors_short492+ sub_group_info,493+ pretty_errors_short=pretty_errors_short,494+ rich_markup_mode=rich_markup_mode,495 )496 if sub_group.name:497 commands[sub_group.name] = sub_group498 solved_info = solve_typer_info_defaults(group_info)2 unmodified lines501 convertors,502 context_param_name,503 ) = get_params_convertors_ctx_param_name_from_function(solved_info.callback)504 cls = solved_info.cls or TyperGroup475- group = cls( # type: ignore505+ assert issubclass(cls, TyperGroup)506+ group = cls(507 name=solved_info.name or "",508 commands=commands,509 invoke_without_command=solved_info.invoke_without_command,510 no_args_is_help=solved_info.no_args_is_help,7 unmodified lines518 convertors=convertors,519 context_param_name=context_param_name,520 pretty_errors_short=pretty_errors_short,521 ),491- params=params, # type: ignore522+ params=params,523 help=solved_info.help,524 epilog=solved_info.epilog,525 short_help=solved_info.short_help,526 options_metavar=solved_info.options_metavar,527 add_help_option=solved_info.add_help_option,528 hidden=solved_info.hidden,529 deprecated=solved_info.deprecated,530+ rich_markup_mode=rich_markup_mode,531+ # Rich settings532+ rich_help_panel=solved_info.rich_help_panel,533 )534 return group535 536 20 unmodified lines557 return params, convertors, context_param_name558 559 560 def get_command_from_info(527- command_info: CommandInfo, *, pretty_errors_short: bool561+ command_info: CommandInfo,562+ *,563+ pretty_errors_short: bool,564+ rich_markup_mode: MarkupMode,565 ) -> click.Command:566 assert command_info.callback, "A command must have a callback function"567 name = command_info.name or get_command_name(command_info.callback.__name__)568 use_help = command_info.help25 unmodified lines594 add_help_option=command_info.add_help_option,595 no_args_is_help=command_info.no_args_is_help,596 hidden=command_info.hidden,597 deprecated=command_info.deprecated,598+ rich_markup_mode=rich_markup_mode,599+ # Rich settings600+ rich_help_panel=command_info.rich_help_panel,601 )602 return command603 604 292 unmodified lines897 is_eager=parameter_info.is_eager,898 envvar=parameter_info.envvar,899 shell_complete=parameter_info.shell_complete,900 autocompletion=get_param_completion(parameter_info.autocompletion),901+ # Rich settings902+ rich_help_panel=parameter_info.rich_help_panel,903 ),904 convertor,905 )906 elif isinstance(parameter_info, ArgumentInfo):23 unmodified lines930 expose_value=parameter_info.expose_value,931 is_eager=parameter_info.is_eager,932 envvar=parameter_info.envvar,933 autocompletion=get_param_completion(parameter_info.autocompletion),934+ # Rich settings935+ rich_help_panel=parameter_info.rich_help_panel,936 ),937 convertor,938 )939 assert False, "A click.Parameter should be returned" # pragma no cover111 unmodified linesmodified:typer/models.py+30 added-7 removed
13 unmodified lines14 )15 16 import click17 18+from ._compat_utils import _get_click_major19+20 if TYPE_CHECKING: # pragma: no cover21+ if _get_click_major() > 7:19- import click.shell_completion22+ import click.shell_completion23 24+ from .core import TyperCommand, TyperGroup21- from .main import Typer # noqa25+ from .main import Typer26 27 28 NoneType = type(None)29 60 unmodified lines90 def __init__(91 self,92 name: Optional[str] = None,93 *,90- cls: Optional[Type[click.Command]] = None,94+ cls: Optional[Type["TyperCommand"]] = None,95 context_settings: Optional[Dict[Any, Any]] = None,96 callback: Optional[Callable[..., Any]] = None,97 help: Optional[str] = None,98 epilog: Optional[str] = None,2 unmodified lines101 add_help_option: bool = True,102 no_args_is_help: bool = False,103 hidden: bool = False,104 deprecated: bool = False,105+ # Rich settings106+ rich_help_panel: Union[str, None] = None,107 ):108 self.name = name109 self.cls = cls110 self.context_settings = context_settings5 unmodified lines116 self.add_help_option = add_help_option117 self.no_args_is_help = no_args_is_help118 self.hidden = hidden119 self.deprecated = deprecated120+ # Rich settings121+ self.rich_help_panel = rich_help_panel122 123 124 class TyperInfo:125 def __init__(126 self,127 typer_instance: Optional["Typer"] = Default(None),128 *,129 name: Optional[str] = Default(None),122- cls: Optional[Type[click.Command]] = Default(None),130+ cls: Optional[Type["TyperGroup"]] = Default(None),131 invoke_without_command: bool = Default(False),132 no_args_is_help: bool = Default(False),133 subcommand_metavar: Optional[str] = Default(None),134 chain: bool = Default(False),7 unmodified lines142 options_metavar: str = Default("[OPTIONS]"),143 add_help_option: bool = Default(True),144 hidden: bool = Default(False),145 deprecated: bool = Default(False),146+ # Rich settings147+ rich_help_panel: Union[str, None] = Default(None),148 ):149 self.typer_instance = typer_instance150 self.name = name151 self.cls = cls10 unmodified lines162 self.options_metavar = options_metavar163 self.add_help_option = add_help_option164 self.hidden = hidden165 self.deprecated = deprecated166+ self.rich_help_panel = rich_help_panel167 168 169 class ParameterInfo:170 def __init__(25 unmodified lines196 min: Optional[Union[int, float]] = None,197 max: Optional[Union[int, float]] = None,198 clamp: bool = False,199 # DateTime189- formats: Optional[Union[List[str]]] = None,200+ formats: Optional[List[str]] = None,201 # File202 mode: Optional[str] = None,203 encoding: Optional[str] = None,204 errors: Optional[str] = "strict",7 unmodified lines212 readable: bool = True,213 resolve_path: bool = False,214 allow_dash: bool = False,215 path_type: Union[None, Type[str], Type[bytes]] = None,216+ # Rich settings217+ rich_help_panel: Union[str, None] = None,218 ):219 self.default = default220 self.param_decls = param_decls221 self.callback = callback31 unmodified lines253 self.readable = readable254 self.resolve_path = resolve_path255 self.allow_dash = allow_dash256 self.path_type = path_type257+ # Rich settings258+ self.rich_help_panel = rich_help_panel259 260 261 class OptionInfo(ParameterInfo):262 def __init__(34 unmodified lines297 min: Optional[Union[int, float]] = None,298 max: Optional[Union[int, float]] = None,299 clamp: bool = False,300 # DateTime286- formats: Optional[Union[List[str]]] = None,301+ formats: Optional[List[str]] = None,302 # File303 mode: Optional[str] = None,304 encoding: Optional[str] = None,305 errors: Optional[str] = "strict",7 unmodified lines313 readable: bool = True,314 resolve_path: bool = False,315 allow_dash: bool = False,316 path_type: Union[None, Type[str], Type[bytes]] = None,317+ # Rich settings318+ rich_help_panel: Union[str, None] = None,319 ):320 super().__init__(321 default=default,322 param_decls=param_decls,32 unmodified lines355 readable=readable,356 resolve_path=resolve_path,357 allow_dash=allow_dash,358 path_type=path_type,359+ # Rich settings360+ rich_help_panel=rich_help_panel,361 )362 self.prompt = prompt363 self.confirmation_prompt = confirmation_prompt364 self.prompt_required = prompt_required35 unmodified lines400 min: Optional[Union[int, float]] = None,401 max: Optional[Union[int, float]] = None,402 clamp: bool = False,403 # DateTime385- formats: Optional[Union[List[str]]] = None,404+ formats: Optional[List[str]] = None,405 # File406 mode: Optional[str] = None,407 encoding: Optional[str] = None,408 errors: Optional[str] = "strict",7 unmodified lines416 readable: bool = True,417 resolve_path: bool = False,418 allow_dash: bool = False,419 path_type: Union[None, Type[str], Type[bytes]] = None,420+ # Rich settings421+ rich_help_panel: Union[str, None] = None,422 ):423 super().__init__(424 default=default,425 param_decls=param_decls,32 unmodified lines458 readable=readable,459 resolve_path=resolve_path,460 allow_dash=allow_dash,461 path_type=path_type,462+ # Rich settings463+ rich_help_panel=rich_help_panel,464 )465 466 467 class ParamMeta:25 unmodified linesmodified:typer/params.py+10 added-2 removed
43 unmodified lines44 min: Optional[Union[int, float]] = None,45 max: Optional[Union[int, float]] = None,46 clamp: bool = False,47 # DateTime48- formats: Optional[Union[List[str]]] = None,48+ formats: Optional[List[str]] = None,49 # File50 mode: Optional[str] = None,51 encoding: Optional[str] = None,52 errors: Optional[str] = "strict",7 unmodified lines60 readable: bool = True,61 resolve_path: bool = False,62 allow_dash: bool = False,63 path_type: Union[None, Type[str], Type[bytes]] = None,64+ # Rich settings65+ rich_help_panel: Union[str, None] = None,66 ) -> Any:67 return OptionInfo(68 # Parameter69 default=default,41 unmodified lines111 readable=readable,112 resolve_path=resolve_path,113 allow_dash=allow_dash,114 path_type=path_type,115+ # Rich settings116+ rich_help_panel=rich_help_panel,117 )118 119 120 def Argument(24 unmodified lines145 min: Optional[Union[int, float]] = None,146 max: Optional[Union[int, float]] = None,147 clamp: bool = False,148 # DateTime145- formats: Optional[Union[List[str]]] = None,149+ formats: Optional[List[str]] = None,150 # File151 mode: Optional[str] = None,152 encoding: Optional[str] = None,153 errors: Optional[str] = "strict",7 unmodified lines161 readable: bool = True,162 resolve_path: bool = False,163 allow_dash: bool = False,164 path_type: Union[None, Type[str], Type[bytes]] = None,165+ # Rich settings166+ rich_help_panel: Union[str, None] = None,167 ) -> Any:168 return ArgumentInfo(169 # Parameter170 default=default,35 unmodified lines206 readable=readable,207 resolve_path=resolve_path,208 allow_dash=allow_dash,209 path_type=path_type,210+ # Rich settings211+ rich_help_panel=rich_help_panel,212 )added:typer/rich_utils.py+693 added
1+# Extracted and modified from https://github.com/ewels/rich-click2+3+import inspect4+import sys5+from collections import defaultdict6+from os import getenv7+from typing import Any, DefaultDict, Dict, Iterable, List, Optional, Union8+9+import click10+from rich import box11+from rich.align import Align12+from rich.columns import Columns13+from rich.console import Console, RenderableType, group14+from rich.emoji import Emoji15+from rich.highlighter import RegexHighlighter16+from rich.markdown import Markdown17+from rich.padding import Padding18+from rich.panel import Panel19+from rich.table import Table20+from rich.text import Text21+from rich.theme import Theme22+23+if sys.version_info >= (3, 8):24+ from typing import Literal25+else:26+ from typing_extensions import Literal27+28+# Default styles29+STYLE_OPTION = "bold cyan"30+STYLE_SWITCH = "bold green"31+STYLE_NEGATIVE_OPTION = "bold magenta"32+STYLE_NEGATIVE_SWITCH = "bold red"33+STYLE_METAVAR = "bold yellow"34+STYLE_METAVAR_SEPARATOR = "dim"35+STYLE_USAGE = "yellow"36+STYLE_USAGE_COMMAND = "bold"37+STYLE_DEPRECATED = "red"38+STYLE_DEPRECATED_COMMAND = "dim"39+STYLE_HELPTEXT_FIRST_LINE = ""40+STYLE_HELPTEXT = "dim"41+STYLE_OPTION_HELP = ""42+STYLE_OPTION_DEFAULT = "dim"43+STYLE_OPTION_ENVVAR = "dim yellow"44+STYLE_REQUIRED_SHORT = "red"45+STYLE_REQUIRED_LONG = "dim red"46+STYLE_OPTIONS_PANEL_BORDER = "dim"47+ALIGN_OPTIONS_PANEL: Literal["left", "center", "right"] = "left"48+STYLE_OPTIONS_TABLE_SHOW_LINES = False49+STYLE_OPTIONS_TABLE_LEADING = 050+STYLE_OPTIONS_TABLE_PAD_EDGE = False51+STYLE_OPTIONS_TABLE_PADDING = (0, 1)52+STYLE_OPTIONS_TABLE_BOX = ""53+STYLE_OPTIONS_TABLE_ROW_STYLES = None54+STYLE_OPTIONS_TABLE_BORDER_STYLE = None55+STYLE_COMMANDS_PANEL_BORDER = "dim"56+ALIGN_COMMANDS_PANEL: Literal["left", "center", "right"] = "left"57+STYLE_COMMANDS_TABLE_SHOW_LINES = False58+STYLE_COMMANDS_TABLE_LEADING = 059+STYLE_COMMANDS_TABLE_PAD_EDGE = False60+STYLE_COMMANDS_TABLE_PADDING = (0, 1)61+STYLE_COMMANDS_TABLE_BOX = ""62+STYLE_COMMANDS_TABLE_ROW_STYLES = None63+STYLE_COMMANDS_TABLE_BORDER_STYLE = None64+STYLE_ERRORS_PANEL_BORDER = "red"65+ALIGN_ERRORS_PANEL: Literal["left", "center", "right"] = "left"66+STYLE_ERRORS_SUGGESTION = "dim"67+STYLE_ABORTED = "red"68+_TERMINAL_WIDTH = getenv("TERMINAL_WIDTH")69+MAX_WIDTH = int(_TERMINAL_WIDTH) if _TERMINAL_WIDTH else None70+COLOR_SYSTEM: Optional[71+ Literal["auto", "standard", "256", "truecolor", "windows"]72+] = "auto" # Set to None to disable colors73+_TYPER_FORCE_DISABLE_TERMINAL = getenv("_TYPER_FORCE_DISABLE_TERMINAL")74+FORCE_TERMINAL = bool(75+ not _TYPER_FORCE_DISABLE_TERMINAL76+ and getenv("GITHUB_ACTIONS")77+ or getenv("FORCE_COLOR")78+ or getenv("PY_COLORS")79+)80+81+# Fixed strings82+DEPRECATED_STRING = "(deprecated) "83+DEFAULT_STRING = "[default: {}]"84+ENVVAR_STRING = "[env var: {}]"85+REQUIRED_SHORT_STRING = "*"86+REQUIRED_LONG_STRING = "[required]"87+RANGE_STRING = " [{}]"88+ARGUMENTS_PANEL_TITLE = "Arguments"89+OPTIONS_PANEL_TITLE = "Options"90+COMMANDS_PANEL_TITLE = "Commands"91+ERRORS_PANEL_TITLE = "Error"92+ABORTED_TEXT = "Aborted."93+94+MARKUP_MODE_MARKDOWN = "markdown"95+MARKUP_MODE_RICH = "rich"96+_RICH_HELP_PANEL_NAME = "rich_help_panel"97+98+MarkupMode = Literal["markdown", "rich", None]99+100+101+# Rich regex highlighter102+class OptionHighlighter(RegexHighlighter):103+ """Highlights our special options."""104+105+ highlights = [106+ r"(^|\W)(?P<switch>\-\w+)(?![a-zA-Z0-9])",107+ r"(^|\W)(?P<option>\-\-[\w\-]+)(?![a-zA-Z0-9])",108+ r"(?P<metavar>\<[^\>]+\>)",109+ r"(?P<usage>Usage: )",110+ ]111+112+113+class NegativeOptionHighlighter(RegexHighlighter):114+ highlights = [115+ r"(^|\W)(?P<negative_switch>\-\w+)(?![a-zA-Z0-9])",116+ r"(^|\W)(?P<negative_option>\-\-[\w\-]+)(?![a-zA-Z0-9])",117+ ]118+119+120+highlighter = OptionHighlighter()121+negative_highlighter = NegativeOptionHighlighter()122+123+124+def _get_rich_console(stderr: bool = False) -> Console:125+ return Console(126+ theme=Theme(127+ {128+ "option": STYLE_OPTION,129+ "switch": STYLE_SWITCH,130+ "negative_option": STYLE_NEGATIVE_OPTION,131+ "negative_switch": STYLE_NEGATIVE_SWITCH,132+ "metavar": STYLE_METAVAR,133+ "metavar_sep": STYLE_METAVAR_SEPARATOR,134+ "usage": STYLE_USAGE,135+ },136+ ),137+ highlighter=highlighter,138+ color_system=COLOR_SYSTEM,139+ force_terminal=FORCE_TERMINAL,140+ width=MAX_WIDTH,141+ stderr=stderr,142+ )143+144+145+def _make_rich_rext(146+ *, text: str, style: str = "", markup_mode: MarkupMode147+) -> Union[Markdown, Text]:148+ """Take a string, remove indentations, and return styled text.149+150+ By default, return the text as a Rich Text with the request style.151+ If `rich_markdown_enable` is `True`, also parse the text for Rich markup strings.152+ If `rich_markup_enable` is `True`, parse as Markdown.153+154+ Only one of `rich_markdown_enable` or `rich_markup_enable` can be True.155+ If both are True, `rich_markdown_enable` takes precedence.156+ """157+ # Remove indentations from input text158+ text = inspect.cleandoc(text)159+ if markup_mode == MARKUP_MODE_MARKDOWN:160+ text = Emoji.replace(text)161+ return Markdown(text, style=style)162+ if markup_mode == MARKUP_MODE_RICH:163+ return highlighter(Text.from_markup(text, style=style))164+ else:165+ return highlighter(Text(text, style=style))166+167+168+@group()169+def _get_help_text(170+ *,171+ obj: Union[click.Command, click.Group],172+ markup_mode: MarkupMode,173+) -> Iterable[Union[Markdown, Text]]:174+ """Build primary help text for a click command or group.175+176+ Returns the prose help text for a command or group, rendered either as a177+ Rich Text object or as Markdown.178+ If the command is marked as deprecated, the deprecated string will be prepended.179+ """180+ # Prepend deprecated status181+ if obj.deprecated:182+ yield Text(DEPRECATED_STRING, style=STYLE_DEPRECATED)183+184+ # Fetch and dedent the help text185+ help_text = inspect.cleandoc(obj.help or "")186+187+ # Trim off anything that comes after \f on its own line188+ help_text = help_text.partition("\f")[0]189+190+ # Get the first paragraph191+ first_line = help_text.split("\n\n")[0]192+ # Remove single linebreaks193+ if markup_mode != MARKUP_MODE_MARKDOWN and not first_line.startswith("\b"):194+ first_line = first_line.replace("\n", " ")195+ yield _make_rich_rext(196+ text=first_line.strip(),197+ style=STYLE_HELPTEXT_FIRST_LINE,198+ markup_mode=markup_mode,199+ )200+201+ # Get remaining lines, remove single line breaks and format as dim202+ remaining_paragraphs = help_text.split("\n\n")[1:]203+ if remaining_paragraphs:204+ if markup_mode != MARKUP_MODE_RICH:205+ # Remove single linebreaks206+ remaining_paragraphs = [207+ x.replace("\n", " ").strip()208+ if not x.startswith("\b")209+ else "{}\n".format(x.strip("\b\n"))210+ for x in remaining_paragraphs211+ ]212+ # Join back together213+ remaining_lines = "\n".join(remaining_paragraphs)214+ else:215+ # Join with double linebreaks if markdown216+ remaining_lines = "\n\n".join(remaining_paragraphs)217+218+ yield _make_rich_rext(219+ text=remaining_lines,220+ style=STYLE_HELPTEXT,221+ markup_mode=markup_mode,222+ )223+224+225+def _get_parameter_help(226+ *,227+ param: Union[click.Option, click.Argument, click.Parameter],228+ ctx: click.Context,229+ markup_mode: MarkupMode,230+) -> Columns:231+ """Build primary help text for a click option or argument.232+233+ Returns the prose help text for an option or argument, rendered either234+ as a Rich Text object or as Markdown.235+ Additional elements are appended to show the default and required status if236+ applicable.237+ """238+ # import here to avoid cyclic imports239+ from .core import TyperArgument, TyperOption240+241+ items: List[Union[Text, Markdown]] = []242+243+ # Get the environment variable first244+245+ envvar = getattr(param, "envvar", None)246+ var_str = ""247+ # https://github.com/pallets/click/blob/0aec1168ac591e159baf6f61026d6ae322c53aaf/src/click/core.py#L2720-L2726248+ if envvar is None:249+ if (250+ getattr(param, "allow_from_autoenv", None)251+ and getattr(ctx, "auto_envvar_prefix", None) is not None252+ and param.name is not None253+ ):254+ envvar = f"{ctx.auto_envvar_prefix}_{param.name.upper()}"255+ if envvar is not None:256+ var_str = (257+ envvar if isinstance(envvar, str) else ", ".join(str(d) for d in envvar)258+ )259+260+ # Main help text261+ help_value: Union[str, None] = getattr(param, "help", None)262+ if help_value:263+ paragraphs = help_value.split("\n\n")264+ # Remove single linebreaks265+ if markup_mode != MARKUP_MODE_MARKDOWN:266+ paragraphs = [267+ x.replace("\n", " ").strip()268+ if not x.startswith("\b")269+ else "{}\n".format(x.strip("\b\n"))270+ for x in paragraphs271+ ]272+ items.append(273+ _make_rich_rext(274+ text="\n".join(paragraphs).strip(),275+ style=STYLE_OPTION_HELP,276+ markup_mode=markup_mode,277+ )278+ )279+280+ # Environment variable AFTER help text281+ if envvar and getattr(param, "show_envvar", None):282+ items.append(Text(ENVVAR_STRING.format(var_str), style=STYLE_OPTION_ENVVAR))283+284+ # Default value285+ # This uses Typer's specific param._get_default_string286+ if isinstance(param, (TyperOption, TyperArgument)):287+ if param.show_default:288+ show_default_is_str = isinstance(param.show_default, str)289+ default_value = param._extract_default_help_str(ctx=ctx)290+ default_str = param._get_default_string(291+ ctx=ctx,292+ show_default_is_str=show_default_is_str,293+ default_value=default_value,294+ )295+ if default_str:296+ items.append(297+ Text(298+ DEFAULT_STRING.format(default_str),299+ style=STYLE_OPTION_DEFAULT,300+ )301+ )302+303+ # Required?304+ if param.required:305+ items.append(Text(REQUIRED_LONG_STRING, style=STYLE_REQUIRED_LONG))306+307+ # Use Columns - this allows us to group different renderable types308+ # (Text, Markdown) onto a single line.309+ return Columns(items)310+311+312+def _make_command_help(313+ *,314+ help_text: str,315+ markup_mode: MarkupMode,316+) -> Union[Text, Markdown]:317+ """Build cli help text for a click group command.318+319+ That is, when calling help on groups with multiple subcommands320+ (not the main help text when calling the subcommand help).321+322+ Returns the first paragraph of help text for a command, rendered either as a323+ Rich Text object or as Markdown.324+ Ignores single newlines as paragraph markers, looks for double only.325+ """326+ paragraphs = inspect.cleandoc(help_text).split("\n\n")327+ # Remove single linebreaks328+ if markup_mode != MARKUP_MODE_RICH and not paragraphs[0].startswith("\b"):329+ paragraphs[0] = paragraphs[0].replace("\n", " ")330+ elif paragraphs[0].startswith("\b"):331+ paragraphs[0] = paragraphs[0].replace("\b\n", "")332+ return _make_rich_rext(333+ text=paragraphs[0].strip(),334+ style=STYLE_OPTION_HELP,335+ markup_mode=markup_mode,336+ )337+338+339+def _print_options_panel(340+ *,341+ name: str,342+ params: Union[List[click.Option], List[click.Argument]],343+ ctx: click.Context,344+ markup_mode: MarkupMode,345+ console: Console,346+) -> None:347+ options_rows: List[List[RenderableType]] = []348+ required_rows: List[Union[str, Text]] = []349+ for param in params:350+ # Short and long form351+ opt_long_strs = []352+ opt_short_strs = []353+ secondary_opt_long_strs = []354+ secondary_opt_short_strs = []355+ for opt_str in param.opts:356+ if "--" in opt_str:357+ opt_long_strs.append(opt_str)358+ else:359+ opt_short_strs.append(opt_str)360+ for opt_str in param.secondary_opts:361+ if "--" in opt_str:362+ secondary_opt_long_strs.append(opt_str)363+ else:364+ secondary_opt_short_strs.append(opt_str)365+366+ # Column for a metavar, if we have one367+ metavar = Text(style=STYLE_METAVAR, overflow="fold")368+ metavar_str = param.make_metavar()369+370+ # Do it ourselves if this is a positional argument371+ if (372+ isinstance(param, click.Argument)373+ and param.name374+ and metavar_str == param.name.upper()375+ ):376+ metavar_str = param.type.name.upper()377+378+ # Skip booleans and choices (handled above)379+ if metavar_str != "BOOLEAN":380+ metavar.append(metavar_str)381+382+ # Range - from383+ # https://github.com/pallets/click/blob/c63c70dabd3f86ca68678b4f00951f78f52d0270/src/click/core.py#L2698-L2706 # noqa: E501384+ try:385+ # skip count with default range type386+ if (387+ isinstance(param.type, click.types._NumberRangeBase)388+ and isinstance(param, click.Option)389+ and not (param.count and param.type.min == 0 and param.type.max is None)390+ ):391+ range_str = param.type._describe_range()392+ if range_str:393+ metavar.append(RANGE_STRING.format(range_str))394+ except AttributeError: # pragma: no cover395+ # click.types._NumberRangeBase is only in Click 8x onwards396+ pass397+398+ # Required asterisk399+ required: Union[str, Text] = ""400+ if param.required:401+ required = Text(REQUIRED_SHORT_STRING, style=STYLE_REQUIRED_SHORT)402+403+ # Highlighter to make [ | ] and <> dim404+ class MetavarHighlighter(RegexHighlighter):405+ highlights = [406+ r"^(?P<metavar_sep>(\[|<))",407+ r"(?P<metavar_sep>\|)",408+ r"(?P<metavar_sep>(\]|>)$)",409+ ]410+411+ metavar_highlighter = MetavarHighlighter()412+413+ required_rows.append(required)414+ options_rows.append(415+ [416+ highlighter(",".join(opt_long_strs)),417+ highlighter(",".join(opt_short_strs)),418+ negative_highlighter(",".join(secondary_opt_long_strs)),419+ negative_highlighter(",".join(secondary_opt_short_strs)),420+ metavar_highlighter(metavar),421+ _get_parameter_help(422+ param=param,423+ ctx=ctx,424+ markup_mode=markup_mode,425+ ),426+ ]427+ )428+ rows_with_required: List[List[RenderableType]] = []429+ if any(required_rows):430+ for required, row in zip(required_rows, options_rows):431+ rows_with_required.append([required, *row])432+ else:433+ rows_with_required = options_rows434+ if options_rows:435+ t_styles: Dict[str, Any] = {436+ "show_lines": STYLE_OPTIONS_TABLE_SHOW_LINES,437+ "leading": STYLE_OPTIONS_TABLE_LEADING,438+ "box": STYLE_OPTIONS_TABLE_BOX,439+ "border_style": STYLE_OPTIONS_TABLE_BORDER_STYLE,440+ "row_styles": STYLE_OPTIONS_TABLE_ROW_STYLES,441+ "pad_edge": STYLE_OPTIONS_TABLE_PAD_EDGE,442+ "padding": STYLE_OPTIONS_TABLE_PADDING,443+ }444+ box_style = getattr(box, t_styles.pop("box"), None)445+446+ options_table = Table(447+ highlight=True,448+ show_header=False,449+ expand=True,450+ box=box_style,451+ **t_styles,452+ )453+ for row in rows_with_required:454+ options_table.add_row(*row)455+ console.print(456+ Panel(457+ options_table,458+ border_style=STYLE_OPTIONS_PANEL_BORDER,459+ title=name,460+ title_align=ALIGN_OPTIONS_PANEL,461+ )462+ )463+464+465+def _print_commands_panel(466+ *,467+ name: str,468+ commands: List[click.Command],469+ markup_mode: MarkupMode,470+ console: Console,471+) -> None:472+ t_styles: Dict[str, Any] = {473+ "show_lines": STYLE_COMMANDS_TABLE_SHOW_LINES,474+ "leading": STYLE_COMMANDS_TABLE_LEADING,475+ "box": STYLE_COMMANDS_TABLE_BOX,476+ "border_style": STYLE_COMMANDS_TABLE_BORDER_STYLE,477+ "row_styles": STYLE_COMMANDS_TABLE_ROW_STYLES,478+ "pad_edge": STYLE_COMMANDS_TABLE_PAD_EDGE,479+ "padding": STYLE_COMMANDS_TABLE_PADDING,480+ }481+ box_style = getattr(box, t_styles.pop("box"), None)482+483+ commands_table = Table(484+ highlight=False,485+ show_header=False,486+ expand=True,487+ box=box_style,488+ **t_styles,489+ )490+ # Define formatting in first column, as commands don't match highlighter491+ # regex492+ commands_table.add_column(style="bold cyan", no_wrap=True)493+ rows: List[List[Union[RenderableType, None]]] = []494+ deprecated_rows: List[Union[RenderableType, None]] = []495+ for command in commands:496+ helptext = command.short_help or command.help or ""497+ command_name = command.name or ""498+ if command.deprecated:499+ command_name_text = Text(f"{command_name}", style=STYLE_DEPRECATED_COMMAND)500+ deprecated_rows.append(Text(DEPRECATED_STRING, style=STYLE_DEPRECATED))501+ else:502+ command_name_text = Text(command_name)503+ deprecated_rows.append(None)504+ rows.append(505+ [506+ command_name_text,507+ _make_command_help(508+ help_text=helptext,509+ markup_mode=markup_mode,510+ ),511+ ]512+ )513+ rows_with_deprecated = rows514+ if any(deprecated_rows):515+ rows_with_deprecated = []516+ for row, deprecated_text in zip(rows, deprecated_rows):517+ rows_with_deprecated.append([*row, deprecated_text])518+ for row in rows_with_deprecated:519+ commands_table.add_row(*row)520+ if commands_table.row_count:521+ console.print(522+ Panel(523+ commands_table,524+ border_style=STYLE_COMMANDS_PANEL_BORDER,525+ title=name,526+ title_align=ALIGN_COMMANDS_PANEL,527+ )528+ )529+530+531+def rich_format_help(532+ *,533+ obj: Union[click.Command, click.Group],534+ ctx: click.Context,535+ markup_mode: MarkupMode,536+) -> None:537+ """Print nicely formatted help text using rich.538+539+ Based on original code from rich-cli, by @willmcgugan.540+ https://github.com/Textualize/rich-cli/blob/8a2767c7a340715fc6fbf4930ace717b9b2fc5e5/src/rich_cli/__main__.py#L162-L236541+542+ Replacement for the click function format_help().543+ Takes a command or group and builds the help text output.544+ """545+ console = _get_rich_console()546+547+ # Print usage548+ console.print(549+ Padding(highlighter(obj.get_usage(ctx)), 1), style=STYLE_USAGE_COMMAND550+ )551+552+ # Print command / group help if we have some553+ if obj.help:554+555+ # Print with some padding556+ console.print(557+ Padding(558+ Align(559+ _get_help_text(560+ obj=obj,561+ markup_mode=markup_mode,562+ ),563+ pad=False,564+ ),565+ (0, 1, 1, 1),566+ )567+ )568+ panel_to_arguments: DefaultDict[str, List[click.Argument]] = defaultdict(list)569+ panel_to_options: DefaultDict[str, List[click.Option]] = defaultdict(list)570+ for param in obj.get_params(ctx):571+572+ # Skip if option is hidden573+ if getattr(param, "hidden", False):574+ continue575+ if isinstance(param, click.Argument):576+ panel_name = (577+ getattr(param, _RICH_HELP_PANEL_NAME, None) or ARGUMENTS_PANEL_TITLE578+ )579+ panel_to_arguments[panel_name].append(param)580+ elif isinstance(param, click.Option):581+ panel_name = (582+ getattr(param, _RICH_HELP_PANEL_NAME, None) or OPTIONS_PANEL_TITLE583+ )584+ panel_to_options[panel_name].append(param)585+ default_arguments = panel_to_arguments.get(ARGUMENTS_PANEL_TITLE, [])586+ _print_options_panel(587+ name=ARGUMENTS_PANEL_TITLE,588+ params=default_arguments,589+ ctx=ctx,590+ markup_mode=markup_mode,591+ console=console,592+ )593+ for panel_name, arguments in panel_to_arguments.items():594+ if panel_name == ARGUMENTS_PANEL_TITLE:595+ # Already printed above596+ continue597+ _print_options_panel(598+ name=panel_name,599+ params=arguments,600+ ctx=ctx,601+ markup_mode=markup_mode,602+ console=console,603+ )604+ default_options = panel_to_options.get(OPTIONS_PANEL_TITLE, [])605+ _print_options_panel(606+ name=OPTIONS_PANEL_TITLE,607+ params=default_options,608+ ctx=ctx,609+ markup_mode=markup_mode,610+ console=console,611+ )612+ for panel_name, options in panel_to_options.items():613+ if panel_name == OPTIONS_PANEL_TITLE:614+ # Already printed above615+ continue616+ _print_options_panel(617+ name=panel_name,618+ params=options,619+ ctx=ctx,620+ markup_mode=markup_mode,621+ console=console,622+ )623+624+ if isinstance(obj, click.MultiCommand):625+ panel_to_commands: DefaultDict[str, List[click.Command]] = defaultdict(list)626+ for command_name in obj.list_commands(ctx):627+ command = obj.get_command(ctx, command_name)628+ if command and not command.hidden:629+ panel_name = (630+ getattr(command, _RICH_HELP_PANEL_NAME, None)631+ or COMMANDS_PANEL_TITLE632+ )633+ panel_to_commands[panel_name].append(command)634+635+ # Print each command group panel636+ default_commands = panel_to_commands.get(COMMANDS_PANEL_TITLE, [])637+ _print_commands_panel(638+ name=COMMANDS_PANEL_TITLE,639+ commands=default_commands,640+ markup_mode=markup_mode,641+ console=console,642+ )643+ for panel_name, commands in panel_to_commands.items():644+ if panel_name == COMMANDS_PANEL_TITLE:645+ # Already printed above646+ continue647+ _print_commands_panel(648+ name=panel_name,649+ commands=commands,650+ markup_mode=markup_mode,651+ console=console,652+ )653+654+ # Epilogue if we have it655+ if obj.epilog:656+ # Remove single linebreaks, replace double with single657+ lines = obj.epilog.split("\n\n")658+ epilogue = "\n".join([x.replace("\n", " ").strip() for x in lines])659+ epilogue_text = _make_rich_rext(text=epilogue, markup_mode=markup_mode)660+ console.print(Padding(Align(epilogue_text, pad=False), 1))661+662+663+def rich_format_error(self: click.ClickException) -> None:664+ """Print richly formatted click errors.665+666+ Called by custom exception handler to print richly formatted click errors.667+ Mimics original click.ClickException.echo() function but with rich formatting.668+ """669+ console = _get_rich_console(stderr=True)670+ ctx: Union[click.Context, None] = getattr(self, "ctx", None)671+ if ctx is not None:672+ console.print(ctx.get_usage())673+674+ if ctx is not None and ctx.command.get_help_option(ctx) is not None:675+ console.print(676+ f"Try [blue]'{ctx.command_path} {ctx.help_option_names[0]}'[/] for help.",677+ style=STYLE_ERRORS_SUGGESTION,678+ )679+680+ console.print(681+ Panel(682+ highlighter(self.format_message()),683+ border_style=STYLE_ERRORS_PANEL_BORDER,684+ title=ERRORS_PANEL_TITLE,685+ title_align=ALIGN_ERRORS_PANEL,686+ )687+ )688+689+690+def rich_abort_error() -> None:691+ """Print richly formatted abort error."""692+ console = _get_rich_console(stderr=True)693+ console.print(ABORTED_TEXT, style=STYLE_ABORTED)modified:typer/utils.py-6 removed
1 import inspect2 from typing import Any, Callable, Dict, get_type_hints3 4-import click5-4 from .models import ParamMeta5 6 7 def get_params_from_function(func: Callable[..., Any]) -> Dict[str, ParamMeta]:7 unmodified lines15 params[param.name] = ParamMeta(16 name=param.name, default=param.default, annotation=annotation17 )18 return params21-22-23-def _get_click_major() -> int:24- return int(click.__version__.split(".")[0])modified:README.md+88 added-59 removed
54 unmodified lines55 56 <div class="termy">57 58 ```console59-$ pip install typer59+$ pip install "typer[all]"60 ---> 100%61 Successfully installed typer62 ```63 64 </div>65 66+**Note**: that will include <a href="https://rich.readthedocs.io/" class="external-link" target="_blank">Rich</a>. Rich is the recommended library to *display* information on the terminal, it is optional, but when installed, it's deeply integrated into **Typer** to display beautiful output.67+68 ## Example69 70 ### The absolute minimum71 3 unmodified lines75 import typer76 77 78 def main(name: str):77- typer.echo(f"Hello {name}")79+ print(f"Hello {name}")80 81 82 if __name__ == "__main__":83 typer.run(main)9 unmodified lines93 // Run your application94 $ python main.py95 96 // You get a nice error, you are missing NAME95-Usage: main.py [OPTIONS] NAME96-Try "main.py --help" for help.97+<font color="#F4BF75">Usage: </font>main.py [OPTIONS] NAME98+<font color="#A5A5A1">Try </font><font color="#44919F">'main.py </font><font color="#44919F"><b>--help</b></font><font color="#44919F">'</font><font color="#A5A5A1"> for help.</font>99+<font color="#F92672">╭─ Error ───────────────────────────────────────────╮</font>100+<font color="#F92672">│</font> Missing argument 'NAME'. <font color="#F92672">│</font>101+<font color="#F92672">╰───────────────────────────────────────────────────╯</font>102 98-Error: Missing argument 'NAME'.103 104 // You get a --help for free105 $ python main.py --help106 103-Usage: main.py [OPTIONS] NAME107+<b> </b><font color="#F4BF75"><b>Usage: </b></font><b>main.py [OPTIONS] NAME </b>108+<b> </b>109+<font color="#A5A5A1">╭─ Arguments ───────────────────────────────────────╮</font>110+<font color="#A5A5A1">│ </font><font color="#F92672">*</font> name <font color="#F4BF75"><b>TEXT</b></font> [default: None] <font color="#A6194C">[required]</font> │111+<font color="#A5A5A1">╰───────────────────────────────────────────────────╯</font>112+<font color="#A5A5A1">╭─ Options ─────────────────────────────────────────╮</font>113+<font color="#A5A5A1">│ </font><font color="#A1EFE4"><b>--install-completion</b></font> Install completion │114+<font color="#A5A5A1">│ for the current │</font>115+<font color="#A5A5A1">│ shell. │</font>116+<font color="#A5A5A1">│ </font><font color="#A1EFE4"><b>--show-completion</b></font> Show completion for │117+<font color="#A5A5A1">│ the current shell, │</font>118+<font color="#A5A5A1">│ to copy it or │</font>119+<font color="#A5A5A1">│ customize the │</font>120+<font color="#A5A5A1">│ installation. │</font>121+<font color="#A5A5A1">│ </font><font color="#A1EFE4"><b>--help</b></font> Show this message │122+<font color="#A5A5A1">│ and exit. │</font>123+<font color="#A5A5A1">╰───────────────────────────────────────────────────╯</font>124 105-Arguments:106- NAME [required]107-108-Options:109- --install-completion Install completion for the current shell.110- --show-completion Show completion for the current shell, to copy it or customize the installation.111- --help Show this message and exit.112-125 // When you create a package you get ✨ auto-completion ✨ for free, installed with --install-completion126 127 // Now pass the NAME argument128 $ python main.py Camila26 unmodified lines155 156 157 @app.command()158 def hello(name: str):147- typer.echo(f"Hello {name}")159+ print(f"Hello {name}")160 161 162 @app.command()163 def goodbye(name: str, formal: bool = False):164 if formal:153- typer.echo(f"Goodbye Ms. {name}. Have a good day.")165+ print(f"Goodbye Ms. {name}. Have a good day.")166 else:155- typer.echo(f"Bye {name}!")167+ print(f"Bye {name}!")168 169 170 if __name__ == "__main__":171 app()7 unmodified lines179 * Execute the `app()` itself, as if it was a function (instead of `typer.run`).180 181 ### Run the upgraded example182 183+Check the new help:184+185 <div class="termy">186 187 ```console174-// Check the --help188 $ python main.py --help189 177-Usage: main.py [OPTIONS] COMMAND [ARGS]...190+<b> </b><font color="#F4BF75"><b>Usage: </b></font><b>main.py [OPTIONS] COMMAND [ARGS]... </b>191+<b> </b>192+<font color="#A5A5A1">╭─ Options ─────────────────────────────────────────╮</font>193+<font color="#A5A5A1">│ </font><font color="#A1EFE4"><b>--install-completion</b></font> Install completion │194+<font color="#A5A5A1">│ for the current │</font>195+<font color="#A5A5A1">│ shell. │</font>196+<font color="#A5A5A1">│ </font><font color="#A1EFE4"><b>--show-completion</b></font> Show completion for │197+<font color="#A5A5A1">│ the current shell, │</font>198+<font color="#A5A5A1">│ to copy it or │</font>199+<font color="#A5A5A1">│ customize the │</font>200+<font color="#A5A5A1">│ installation. │</font>201+<font color="#A5A5A1">│ </font><font color="#A1EFE4"><b>--help</b></font> Show this message │202+<font color="#A5A5A1">│ and exit. │</font>203+<font color="#A5A5A1">╰───────────────────────────────────────────────────╯</font>204+<font color="#A5A5A1">╭─ Commands ────────────────────────────────────────╮</font>205+<font color="#A5A5A1">│ </font><font color="#A1EFE4"><b>goodbye </b></font> │206+<font color="#A5A5A1">│ </font><font color="#A1EFE4"><b>hello </b></font> │207+<font color="#A5A5A1">╰───────────────────────────────────────────────────╯</font>208 179-Options:180- --install-completion Install completion for the current shell.181- --show-completion Show completion for the current shell, to copy it or customize the installation.182- --help Show this message and exit.209+// You have 2 subcommands (the 2 functions): goodbye and hello210+```211 184-Commands:185- goodbye186- hello212+</div>213 188-// You have 2 subcommands (the 2 functions): goodbye and hello214+Now check the help for the `hello` command:215 190-// Now get the --help for hello216+<div class="termy">217 218+```console219 $ python main.py hello --help220 194-Usage: main.py hello [OPTIONS] NAME221+<b> </b><font color="#F4BF75"><b>Usage: </b></font><b>main.py hello [OPTIONS] NAME </b>222+<b> </b>223+<font color="#A5A5A1">╭─ Arguments ───────────────────────────────────────╮</font>224+<font color="#A5A5A1">│ </font><font color="#F92672">*</font> name <font color="#F4BF75"><b>TEXT</b></font> [default: None] <font color="#A6194C">[required]</font> │225+<font color="#A5A5A1">╰───────────────────────────────────────────────────╯</font>226+<font color="#A5A5A1">╭─ Options ─────────────────────────────────────────╮</font>227+<font color="#A5A5A1">│ </font><font color="#A1EFE4"><b>--help</b></font> Show this message and exit. │228+<font color="#A5A5A1">╰───────────────────────────────────────────────────╯</font>229+```230 196-Arguments:197- NAME [required]231+</div>232 199-Options:200- --help Show this message and exit.233+And now check the help for the `goodbye` command:234 202-// And now get the --help for goodbye235+<div class="termy">236 237+```console238 $ python main.py goodbye --help239 206-Usage: main.py goodbye [OPTIONS] NAME240+<b> </b><font color="#F4BF75"><b>Usage: </b></font><b>main.py goodbye [OPTIONS] NAME </b>241+<b> </b>242+<font color="#A5A5A1">╭─ Arguments ───────────────────────────────────────╮</font>243+<font color="#A5A5A1">│ </font><font color="#F92672">*</font> name <font color="#F4BF75"><b>TEXT</b></font> [default: None] <font color="#A6194C">[required]</font> │244+<font color="#A5A5A1">╰───────────────────────────────────────────────────╯</font>245+<font color="#A5A5A1">╭─ Options ─────────────────────────────────────────╮</font>246+<font color="#A5A5A1">│ </font><font color="#A1EFE4"><b>--formal</b></font> <font color="#AE81FF"><b>--no-formal</b></font> [default: no-formal] │247+<font color="#A5A5A1">│ </font><font color="#A1EFE4"><b>--help</b></font> Show this message │248+<font color="#A5A5A1">│ and exit. │</font>249+<font color="#A5A5A1">╰───────────────────────────────────────────────────╯</font>250 208-Arguments:209- NAME [required]251+// Automatic --formal and --no-formal for the bool option 🎉252+```253 211-Options:212- --formal / --no-formal [default: False]213- --help Show this message and exit.254+</div>255 215-// Automatic --formal and --no-formal for the bool option 🎉256+Now you can try out the new command line application:257 217-// And if you use it with the hello command258+<div class="termy">259 260+```console261+// Use it with the hello command262+263 $ python main.py hello Camila264 265 Hello Camila266 47 unmodified lines314 Typer uses <a href="https://click.palletsprojects.com/" class="external-link" target="_blank">Click</a> internally. That's the only dependency.315 316 But you can also install extras:317 274-* <a href="https://rich.readthedocs.io/en/stable/index.html" class="external-link" target="_blank">Rich</a>: and Typer will show nicely formatted errors automatically.275-* <a href="https://pypi.org/project/colorama/" class="external-link" target="_blank"><code>colorama</code></a>: and Click will automatically use it to make sure your terminal's colors always work correctly, even in Windows.276- * Then you can use any tool you want to output your terminal's colors in all the systems, including the integrated `typer.style()` and `typer.secho()` (provided by Click).277- * Or any other tool, e.g. <a href="https://pypi.org/project/wasabi/" class="external-link" target="_blank"><code>wasabi</code></a>, <a href="https://github.com/erikrose/blessings" class="external-link" target="_blank"><code>blessings</code></a>.318+* <a href="https://rich.readthedocs.io/en/stable/index.html" class="external-link" target="_blank"><code>rich</code></a>: and Typer will show nicely formatted errors automatically.319 * <a href="https://github.com/sarugaku/shellingham" class="external-link" target="_blank"><code>shellingham</code></a>: and Typer will automatically detect the current shell when installing completion.320 * With `shellingham` you can just use `--install-completion`.321 * Without `shellingham`, you have to pass the name of the shell to install completion for, e.g. `--install-completion bash`.322 282-You can install `typer` with `colorama` and `shellingham` with `pip install typer[all]`.323+You can install `typer` with `rich` and `shellingham` with `pip install typer[all]`.324 284-## Other tools and plug-ins285-286-Click has many plug-ins available that you can use. And there are many tools that help with command line applications that you can use as well, even if they are not related to Typer or Click.287-288-For example:289-290-* <a href="https://github.com/click-contrib/click-spinner" class="external-link" target="_blank"><code>click-spinner</code></a>: to show the user that you are loading data. A Click plug-in.291- * There are several other Click plug-ins at <a href="https://github.com/click-contrib" class="external-link" target="_blank">click-contrib</a> that you can explore.292-* <a href="https://pypi.org/project/tabulate/" class="external-link" target="_blank"><code>tabulate</code></a>: to automatically display tabular data nicely. Independent of Click or Typer.293-* <a href="https://github.com/tqdm/tqdm" class="external-link" target="_blank"><code>tqdm</code></a>: a fast, extensible progress bar, alternative to Typer's own `typer.progressbar()`.294-* etc... you can re-use many of the great available tools for building CLIs.295-325 ## License326 327 This project is licensed under the terms of the MIT license.