Skip to content
Myr

✨ 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

250 files+3488 added−705 removed

modified:docs/css/termynal.css+3 added-1 removed
modified:docs/tutorial/arguments/help.md+51 added-1 removed
209 unmodified lines
210```211212</div>213214## *CLI Argument* help panels215216You might want to show the help information for *CLI arguments* in different panels when using the `--help` option.217218If 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:219220```Python hl_lines="7 10"221{!../docs_src/arguments/help/tutorial007.py!}222```223224Then, 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`.225226And next you will see other panels for the *CLI arguments* that have a custom panel set in the `rich_help_panel` parameter:227228<div class="termy">229230```console231$ python main.py --help232233<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.236237<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&apos;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```253254</div>255256In this example we have a custom *CLI arguments* panel named "`Secondary Arguments`".257258## Help with style using Rich259260In 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}.261262If 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.263264## Hide a *CLI argument* from the help text265266If you want, you can make a *CLI argument* **not** show up in the `Arguments` section in the help text.267268You will probably not want to do this normally, but it's possible:269270```Python hl_lines="4"221{!../docs_src/arguments/help/tutorial007.py!}271{!../docs_src/arguments/help/tutorial008.py!}272```273274Check it:275
45 unmodified lines
modified:docs/tutorial/commands/help.md+366 added
116 unmodified lines
117// It uses "Create a new user with USERNAME." instead of "Some internal utility function to create."118```119120</div>121122## Deprecate a Command123124There 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.125126You can mark it with the parameter `deprecated=True`:127128```Python hl_lines="14"129{!../docs_src/commands/help/tutorial003.py!}130```131132And when you show the `--help` option you will see it's marked as "`deprecated`":133134<div class="termy">135136```console137$ python main.py --help138139<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```154155</div>156157And if you check the `--help` for the deprecated command (in this example, the command `delete`), it also shows it as deprecated:158159<div class="termy">160161```console162$ python main.py delete --help163164<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.169170<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```177178</div>179180## Rich Markdown and Markup181182If 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`.183184Then 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. 👇185186!!! info187 By default, `rich_markup_mode` is `None`, which disables any rich text formatting.188189### Rich Markup190191If 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:192193```Python hl_lines="3 9 13-15 20 22 24"194{!../docs_src/commands/help/tutorial004.py!}195```196197With 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>.198199You can also use markup in the help for the `username` CLI Argument.200201And 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.202203If you run the program and check the help, you will see that **Typer** uses **Rich** internally to format the help.204205Check the help for the `create` command:206207<div class="termy">208209```console210$ python main.py create --help211212<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>216217<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```226227</div>228229And check the help for the `delete` command:230231<div class="termy">232233```console234$ python main.py delete --help235236<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>.239240<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```251252</div>253254### Rich Markown255256If you set `rich_markup_mode="markdown"` when creating the `typer.Typer()` app, you will be able to use Markdown in the docstring:257258```Python hl_lines="3 7 9-17 22 24-25"259{!../docs_src/commands/help/tutorial005.py!}260```261262With 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>.263264And the same as before, the help text overwritten for the command `delete` can also use Markdown.265266Check the help for the `create` command:267268<div class="termy">269270```console271$ python main.py create --help272273<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. ✨276277 <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>279280 <font color="#F4BF75">───────────────────────────────────────────────────────────────────</font>281 Learn more at the <font color="#44919F">Typer docs website</font>282283<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```292293</div>294295And the same for the `delete` command:296297<div class="termy">298299```console300$ python main.py delete --help301302<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>.305306<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```317318</div>319320!!! info321 Notice that in Markdown you cannot define colors. For colors you might prefer to use Rich markup.322323## Help Panels324325If you have many commands or CLI parameters, you might want to show their documentation in different panels when using the `--help` option.326327If 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.328329### Help Panels for Commands330331To set the panel for a command you can pass the argument `rich_help_panel` with the name of the panel you want to use:332333```Python hl_lines="22 30 38 46"334{!../docs_src/commands/help/tutorial006.py!}335```336337Commands without a panel will be shown in the default panel `Commands`, and the rest will be shown in the next panels:338339<div class="termy">340341```console342$ python main.py --help343344<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```367368</div>369370### Help Panels for CLI Parameters371372The same way, you can configure the panels for *CLI arguments* and *CLI options* with `rich_help_panel`.373374And of course, in the same application you can also set the `rich_help_panel` for commands.375376```Python hl_lines="12 16 21 30"377{!../docs_src/commands/help/tutorial007.py!}378```379380Then if you run the application you will see all the *CLI parameters* in their respective panels.381382* 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`".386387You can check the `--help` option for the command `create`:388389<div class="termy">390391```console392$ python main.py create --help393394<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. ✨397398<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```418419</div>420421And of course, the `rich_help_panel` can be used in the same way for commands in the same application.422423And those panels will be shown when you use the main `--help` option.424425<div class="termy">426427```console428$ python main.py --help429430<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```447448</div>449450You can see the custom panel for the commands for "`Utils and Configs`".451452## Epilog453454If you need, you can also add an epilog section to the help of your commands:455456```Python hl_lines="6"457{!../docs_src/commands/help/tutorial008.py!}458```459460And when you check the `--help` option it will look like:461462<div class="termy">463464```console465$ python main.py --help466467<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. ✨470471<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>482483 Made with ❤ in <font color="#66D9EF">Venus</font>484```485486</div>
modified:docs/tutorial/options/autocompletion.md+7 added-4 removed
275 unmodified lines
276 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}.277278The completion system only reads from "standard output", so, printing to "standard error" won't break completion. 🚀279280You can print to "standard error" with `typer.echo("some text", err=True)`.280You can print to "standard error" with a **Rich** `Console(stderr=True)`.281282Using `err=True` tells **Typer** (actually Click) that the output should be shown in "standard error".282Using `stderr=True` tells **Rich** that the output should be shown in "standard error".283284```Python hl_lines="12 13"284```Python hl_lines="12 15-16"285{!../docs_src/options/autocompletion/tutorial008.py!}286```287288!!! 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.290291We get all the *CLI parameters* as a raw `list` of `str` by declaring a parameter with type `List[str]`, here it's named `args`.292293!!! tip294 Here we name the list of all the raw *CLI parameters* `args` because that's the convention with Click.
26 unmodified lines
321## Getting the Context and the raw *CLI parameters*322323Of course, you can declare everything if you need it, the context, the raw *CLI parameters*, and the incomplete `str`:324322```Python hl_lines="12"325```Python hl_lines="15"326{!../docs_src/options/autocompletion/tutorial009.py!}327```328329Check it:
37 unmodified lines
modified:docs/tutorial/options/help.md+56 added-1 removed
60 unmodified lines
61```6263</div>6465## *CLI Options* help panels6667The same as with *CLI arguments*, you can put the help for some *CLI options* in different panels to be shown with the `--help` option.6869If 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*:7071```Python hl_lines="8 11"72{!../docs_src/options/help/tutorial002.py!}73```7475Now, 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`.7677And below you will see other panels for the *CLI options* that have a custom panel set in the `rich_help_panel` parameter:7879<div class="termy">8081```console82$ python main.py --help8384<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>8889<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```108109</div>110111Here we have a custom *CLI options* panel named "`Customization and Utils`".112113## Help with style using Rich114115In 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}.116117If 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.118119120## Hide default from help121122You can tell Typer to not show the default value in the help text with `show_default=False`:123124```Python hl_lines="4"70{!../docs_src/options/help/tutorial002.py!}125{!../docs_src/options/help/tutorial003.py!}126```127128And it will no longer show the default value in the help text:129
27 unmodified lines
modified:docs/tutorial/first-steps.md+93 added-62 removed
4 unmodified lines
5```Python6{!../docs_src/first_steps/tutorial001.py!}7```89!!! tip10 You will learn more about `typer.echo()` later in the docs.119Copy that to a file `main.py`.1011Test it:12
8 unmodified lines
2122// Now check the --help23$ python main.py --help2428Usage: main.py [OPTIONS]2930Options: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```4041</div>42
36 unmodified lines
7980$ python main.py8182// If you run it without the argument, it shows a nice error78Usage: main.py [OPTIONS] NAME79Try "main.py --help" for help.83<font color="#F4BF75">Usage: </font>main.py [OPTIONS] NAME84<font color="#A5A5A1">Try </font><font color="#44919F">&apos;main.py </font><font color="#44919F"><b>--help</b></font><font color="#44919F">&apos;</font><font color="#A5A5A1"> for help.</font>85<font color="#F92672">╭─ Error ───────────────────────────────────────────╮</font>86<font color="#F92672">│</font> Missing argument &apos;NAME&apos;. <font color="#F92672">│</font>87<font color="#F92672">╰───────────────────────────────────────────────────╯</font>8881Error: Missing argument 'NAME'.8289// Now pass that NAME CLI argument90$ python main.py Camila9192Hello Camila
26 unmodified lines
119```console120// Check the main --help121$ python main.py --help122117Usage: main.py [OPTIONS] NAME LASTNAME123<font color="#F4BF75">Usage: </font>main.py [OPTIONS] NAME124<font color="#A5A5A1">Try </font><font color="#44919F">&apos;main.py </font><font color="#44919F"><b>--help</b></font><font color="#44919F">&apos;</font><font color="#A5A5A1"> for help.</font>125<font color="#F92672">╭─ Error ───────────────────────────────────────────╮</font>126<font color="#F92672">│</font> Missing argument &apos;NAME&apos;. <font color="#F92672">│</font>127<font color="#F92672">╰───────────────────────────────────────────────────╯</font>128119Arguments: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">&apos;main.py </font><font color="#44919F"><b>--help</b></font><font color="#44919F">&apos;</font><font color="#A5A5A1"> for help.</font>133<font color="#F92672">╭─ Error ───────────────────────────────────────────╮</font>134<font color="#F92672">│</font> Missing argument &apos;NAME&apos;. <font color="#F92672">│</font>135<font color="#F92672">╰───────────────────────────────────────────────────╯</font>136123Options: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.127137// There are now 2 CLI arguments, name and lastname138139// Now pass a single name argument140$ python main.py Camila141133Usage: main.py [OPTIONS] NAME LASTNAME134Try "main.py --help" for help.142<font color="#F4BF75">Usage: </font>main.py [OPTIONS] NAME LASTNAME143<font color="#A5A5A1">Try </font><font color="#44919F">&apos;main.py </font><font color="#44919F"><b>--help</b></font><font color="#44919F">&apos;</font><font color="#A5A5A1"> for help.</font>144<font color="#F92672">╭─ Error ───────────────────────────────────────────╮</font>145<font color="#F92672">│</font> Missing argument &apos;LASTNAME&apos;. <font color="#F92672">│</font>146<font color="#F92672">╰───────────────────────────────────────────────────╯</font>147136Error: Missing argument 'LASTNAME'.137148// These 2 arguments are required, so, pass both:149$ python main.py Camila Gutiérrez150151Hello Camila Gutiérrez
90 unmodified lines
242```console243// Get the help244$ python main.py --help245236Usage: main.py [OPTIONS] NAME LASTNAME237238Arguments:239 NAME [required]240 LASTNAME [required]241242Options: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```264265</div>266
40 unmodified lines
307308```console309$ python main.py --help310295Usage: main.py [OPTIONS] NAME296297Arguments:298 NAME [required]299300Options: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```331332</div>333
48 unmodified lines
382383```console384$ python main.py --help385362Usage: 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>390364 Say hi to NAME, optionally with a --lastname.365366 If --formal is used, say hi very formally.367368Arguments:369 NAME [required]370371Options: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```409410</div>411
111 unmodified lines
modified:docs/tutorial/index.md+3 added-3 removed
modified:docs/tutorial/printing.md+196 added-49 removed
1You can use `typer.echo()` to print to the screen:1You can use the normal `print()` to show information on the screen:23```Python hl_lines="5"4{!../docs_src/first_steps/tutorial001.py!}5```67The 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.7It will show the output normally:89!!! 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>.1112Check it:139<div class="termy">1011```console12$ python main.py
2 unmodified lines
15```1617</div>1824## Color19## Use Rich2026!!! 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>.21You can also display beautiful and more complex information using <a href="https://rich.readthedocs.io/" class="external-link" target="_blank">Rich</a>.2229 You don't need to call `colorama.init()`. Typer (actually Click) will handle it underneath.23### Install Rich2431 And make sure you use `typer.echo()` instead of `print()`.25First, you need to install it:2633!!! 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">2836 So, a colored text is still just a `str`.29```console30// Rich comes with typer[all]31$ pip install "typer[all]"32---> 100%33Successfully installed typer rich3438You 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%38Successfully installed rich39```4041</div>4243### Use Rich `print`4445For the simplest cases, you can just import `print` from `rich` and use it instead of the standard `print`:4640```Python hl_lines="7 9"47```Python hl_lines="2 15"48{!../docs_src/printing/tutorial001.py!}49```5044!!! 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"`.51Just with that, **Rich** will be able to print your data with nice colors and structure:5247 But **Typer** provides them all as variables like `typer.colors.GREEN` just so you can use autocompletion while selecting them.53<div class="termy">5449Check it:55```console56$ python main.py5751<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>58Here's the data59<b>{</b>60 <font color="#A6E22E">&apos;name&apos;</font>: <font color="#A6E22E">&apos;Rick&apos;</font>,61 <font color="#A6E22E">&apos;age&apos;</font>: <font color="#A1EFE4"><b>42</b></font>,62 <font color="#A6E22E">&apos;items&apos;</font>: <b>[</b>63 <b>{</b><font color="#A6E22E">&apos;name&apos;</font>: <font color="#A6E22E">&apos;Portal Gun&apos;</font><b>}</b>,64 <b>{</b><font color="#A6E22E">&apos;name&apos;</font>: <font color="#A6E22E">&apos;Plumbus&apos;</font><b>}</b>65 <b>]</b>,66 <font color="#A6E22E">&apos;active&apos;</font>: <font color="#A6E22E"><i>True</i></font>,67 <font color="#A6E22E">&apos;affiliation&apos;</font>: <font color="#AE81FF"><i>None</i></font>68<b>}</b>69```7071</div>7258You can pass these function arguments to `typer.style()`:73### Rich Markup7460* `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.75Rich 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:7669!!! 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```8072## `typer.secho()` - style and print81<div class="termy">8274There'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.py8576```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```8880Check it:89</div>9082<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>91In this example you can see how to use font styles, colors, and even emojis.9293To learn more check out the <a href="https://rich.readthedocs.io/en/stable/markup.html" class="external-link" target="_blank">Rich docs</a>.9495### Rich Tables9697The way Rich works internally is that it uses a `Console` object to display the information.9899When you call Rich's `print`, it automatically creates this object and uses it.100101But for advanced use cases, you could create a `Console` yourself.102103```Python hl_lines="2-3 5 9-12"104{!../docs_src/printing/tutorial003.py!}105```106107In this example, we create a `Console`, and a `Table`. And then we can add some rows to the table, and print it.108109If you run it, you will see a nicely formatted table:110111<div class="termy">112113```console114$ python main.py115116┏━━━━━━━┳━━━━━━━━━━━━┓117┃<b> Name </b>┃<b> Item </b>┃118┡━━━━━━━╇━━━━━━━━━━━━┩119│ Rick │ Portal Gun │120│ Morty │ Plumbus │121└───────┴────────────┘122```123124</div>125126Rich has many other features, as an example, you can check the docs for:127128* <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.132133### Typer and Rich134135If 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.136137In general, **Typer** tends to be the entry point to your program, taking the first input from the user.138139**Rich** is useful for the parts that need to *display* information. Showing beautiful content on the screen.140141The best results for your command line application would be achieved combining both **Typer** and **Rich**.142143## "Standard Output" and "Standard Error"144145The 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 lines
164 But it will work normally in Bash, Zsh, and Fish.165166### Printing to "standard error"167112You can print to "standard error" with `typer.echo("some text", err=True)`.168You can print to "standard error" creating a Rich `Console` with `stderr=True`.169114Using `err=True` tells **Typer** (actually Click) that the output should be shown in "standard error".170!!! tip171 `stderr` is short for "standard error".172173Using `stderr=True` tells **Rich** that the output should be shown in "standard error".174116```Python hl_lines="5"117{!../docs_src/printing/tutorial003.py!}175```Python hl_lines="4 8"176{!../docs_src/printing/tutorial004.py!}177```178179When you try it in the terminal, it will probably just look the same:180
17 unmodified lines
198199Right now this probably seems quite useless 🤷‍♂.200201But understanding that will come handy in the future, for example for autocompletion and testing.202203## Typer Echo204205!!! 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>.207208 You can probably skip the rest of this section. 🎉😎209210**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.211212For the simplest cases, you can use the standard Python `print()`.213214And for the cases where you want to display data more beautifully, or more advanced content, you should use **Rich** instead.215216### Why `typer.echo`217218`typer.echo()` (which is actually just `click.echo()`) applies some checks to try and convert binary data to strings, and other similar things.219220But 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.221222If you have some `bytes` objects, you would probably want to decode them intentionally and directly before trying to print them.223224And if you want to print data with colors and other features, you are much better off with the more advanced tools in **Rich**.225226!!! 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>.228229### Color230231!!! note "Technical Details"232 The way color works in terminals is by using some codes (ANSI escape sequences) as part of the text.233234 So, a colored text is still just a `str`.235236!!! tip237 Again, you are much better off using <a href="https://rich.readthedocs.io/" class="external-link" target="_blank">Rich</a> for this. 😎238239You 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()`:240241```Python hl_lines="7 9"242{!../docs_src/printing/tutorial005.py!}243```244245!!! 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"`.247248 But **Typer** provides them all as variables like `typer.colors.GREEN` just so you can use autocompletion while selecting them.249250Check it:251252<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>258259You can pass these function arguments to `typer.style()`:260261* `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.269270!!! 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>272273### `typer.secho()` - style and print274275!!! 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. 😎277278There'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()`:279280```Python hl_lines="5"281{!../docs_src/printing/tutorial006.py!}282```283284Check it:285286<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 lines
5556<div class="termy">5758```console59$ pip install typer59$ pip install "typer[all]"60---> 100%61Successfully installed typer62```6364</div>6566**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.6768## Example6970### The absolute minimum71
3 unmodified lines
75import typer767778def main(name: str):77 typer.echo(f"Hello {name}")79 print(f"Hello {name}")808182if __name__ == "__main__":83 typer.run(main)
9 unmodified lines
93// Run your application94$ python main.py9596// You get a nice error, you are missing NAME95Usage: main.py [OPTIONS] NAME96Try "main.py --help" for help.97<font color="#F4BF75">Usage: </font>main.py [OPTIONS] NAME98<font color="#A5A5A1">Try </font><font color="#44919F">&apos;main.py </font><font color="#44919F"><b>--help</b></font><font color="#44919F">&apos;</font><font color="#A5A5A1"> for help.</font>99<font color="#F92672">╭─ Error ───────────────────────────────────────────╮</font>100<font color="#F92672">│</font> Missing argument &apos;NAME&apos;. <font color="#F92672">│</font>101<font color="#F92672">╰───────────────────────────────────────────────────╯</font>10298Error: Missing argument 'NAME'.103104// You get a --help for free105$ python main.py --help106103Usage: 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>124105Arguments:106 NAME [required]107108Options: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.112125// When you create a package you get ✨ auto-completion ✨ for free, installed with --install-completion126127// Now pass the NAME argument128$ python main.py Camila
26 unmodified lines
155156157@app.command()158def hello(name: str):147 typer.echo(f"Hello {name}")159 print(f"Hello {name}")160161162@app.command()163def 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}!")168169170if __name__ == "__main__":171 app()
7 unmodified lines
179* Execute the `app()` itself, as if it was a function (instead of `typer.run`).180181### Run the upgraded example182183Check the new help:184185<div class="termy">186187```console174// Check the --help188$ python main.py --help189177Usage: 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>208179Options: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```211184Commands:185 goodbye186 hello212</div>213188// You have 2 subcommands (the 2 functions): goodbye and hello214Now check the help for the `hello` command:215190// Now get the --help for hello216<div class="termy">217218```console219$ python main.py hello --help220194Usage: 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```230196Arguments:197 NAME [required]231</div>232199Options:200 --help Show this message and exit.233And now check the help for the `goodbye` command:234202// And now get the --help for goodbye235<div class="termy">236237```console238$ python main.py goodbye --help239206Usage: 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>250208Arguments:209 NAME [required]251// Automatic --formal and --no-formal for the bool option 🎉252```253211Options:212 --formal / --no-formal [default: False]213 --help Show this message and exit.254</div>255215// Automatic --formal and --no-formal for the bool option 🎉256Now you can try out the new command line application:257217// And if you use it with the hello command258<div class="termy">259260```console261// Use it with the hello command262263$ python main.py hello Camila264265Hello Camila266
47 unmodified lines
314Typer uses <a href="https://click.palletsprojects.com/" class="external-link" target="_blank">Click</a> internally. That's the only dependency.315316But you can also install extras:317274* <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`.322282You can install `typer` with `colorama` and `shellingham` with `pip install typer[all]`.323You can install `typer` with `rich` and `shellingham` with `pip install typer[all]`.324284## Other tools and plug-ins285286Click 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.287288For example:289290* <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.295325## License326327This project is licensed under the terms of the MIT license.
modified:docs_src/app_dir/tutorial001.py+1 added-1 removed
7 unmodified lines
8def 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")131415if __name__ == "__main__":16 typer.run(main)
modified:docs_src/arguments/default/tutorial001.py+1 added-1 removed
1import typer234def main(name: str = typer.Argument("Wade Wilson")):5 typer.echo(f"Hello {name}")5 print(f"Hello {name}")678if __name__ == "__main__":9 typer.run(main)
modified:docs_src/arguments/default/tutorial002.py+1 added-1 removed
6 unmodified lines
7 return random.choice(["Deadpool", "Rick", "Morty", "Hiro"])8910def main(name: str = typer.Argument(get_name)):11 typer.echo(f"Hello {name}")11 print(f"Hello {name}")121314if __name__ == "__main__":15 typer.run(main)
modified:docs_src/arguments/envvar/tutorial001.py+1 added-1 removed
1import typer234def main(name: str = typer.Argument("World", envvar="AWESOME_NAME")):5 typer.echo(f"Hello Mr. {name}")5 print(f"Hello Mr. {name}")678if __name__ == "__main__":9 typer.run(main)
modified:docs_src/arguments/envvar/tutorial002.py+1 added-1 removed
1import typer234def main(name: str = typer.Argument("World", envvar=["AWESOME_NAME", "GOD_NAME"])):5 typer.echo(f"Hello Mr. {name}")5 print(f"Hello Mr. {name}")678if __name__ == "__main__":9 typer.run(main)
modified:docs_src/arguments/envvar/tutorial003.py+1 added-1 removed
1import typer234def 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}")678if __name__ == "__main__":9 typer.run(main)
modified:docs_src/arguments/help/tutorial001.py+1 added-1 removed
1import typer234def main(name: str = typer.Argument(..., help="The name of the user to greet")):5 typer.echo(f"Hello {name}")5 print(f"Hello {name}")678if __name__ == "__main__":9 typer.run(main)
modified:docs_src/arguments/help/tutorial002.py+1 added-1 removed
3 unmodified lines
4def 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}")91011if __name__ == "__main__":12 typer.run(main)
modified:docs_src/arguments/help/tutorial003.py+1 added-1 removed
3 unmodified lines
4def 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}")91011if __name__ == "__main__":12 typer.run(main)
modified:docs_src/arguments/help/tutorial004.py+1 added-1 removed
3 unmodified lines
4def 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}")91011if __name__ == "__main__":12 typer.run(main)
modified:docs_src/arguments/help/tutorial005.py+1 added-1 removed
4 unmodified lines
5 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}")101112if __name__ == "__main__":13 typer.run(main)
modified:docs_src/arguments/help/tutorial006.py+1 added-1 removed
1import typer234def main(name: str = typer.Argument("World", metavar="✨username✨")):5 typer.echo(f"Hello {name}")5 print(f"Hello {name}")678if __name__ == "__main__":9 typer.run(main)
modified:docs_src/arguments/help/tutorial007.py+10 added-2 removed
1import typer234def main(name: str = typer.Argument("World", hidden=True)):4def 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}")171819if __name__ == "__main__":20 typer.run(main)
added:docs_src/arguments/help/tutorial008.py+12 added
1import typer234def main(name: str = typer.Argument("World", hidden=True)):5 """6 Say hi to NAME very gently, like Dirk.7 """8 print(f"Hello {name}")91011if __name__ == "__main__":12 typer.run(main)
modified:docs_src/arguments/optional/tutorial001.py+1 added-1 removed
1import typer234def main(name: str = typer.Argument(...)):5 typer.echo(f"Hello {name}")5 print(f"Hello {name}")678if __name__ == "__main__":9 typer.run(main)
modified:docs_src/arguments/optional/tutorial002.py+2 added-2 removed
3 unmodified lines
456def 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}")111213if __name__ == "__main__":14 typer.run(main)
modified:docs_src/commands/arguments/tutorial001.py+2 added-2 removed
3 unmodified lines
456@app.command()7def create(username: str):8 typer.echo(f"Creating user: {username}")8 print(f"Creating user: {username}")91011@app.command()12def delete(username: str):13 typer.echo(f"Deleting user: {username}")13 print(f"Deleting user: {username}")141516if __name__ == "__main__":17 app()
modified:docs_src/commands/callback/tutorial001.py+7 added-7 removed
5 unmodified lines
67@app.command()8def 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")141516@app.command()17def 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")232425@app.callback()26def 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"] = True333435if __name__ == "__main__":
1 unmodified line
modified:docs_src/commands/callback/tutorial002.py+2 added-2 removed
1import typer234def callback():5 typer.echo("Running a command")5 print("Running a command")678app = typer.Typer(callback=callback)91011@app.command()12def create(name: str):13 typer.echo(f"Creating user: {name}")13 print(f"Creating user: {name}")141516if __name__ == "__main__":17 app()
modified:docs_src/commands/callback/tutorial003.py+3 added-3 removed
1import typer234def callback():5 typer.echo("Running a command")5 print("Running a command")678app = typer.Typer(callback=callback)91011@app.callback()12def new_callback():13 typer.echo("Override callback, running a command")13 print("Override callback, running a command")141516@app.command()17def create(name: str):18 typer.echo(f"Creating user: {name}")18 print(f"Creating user: {name}")192021if __name__ == "__main__":22 app()
modified:docs_src/commands/callback/tutorial004.py+1 added-1 removed
14 unmodified lines
151617@app.command()18def create(name: str):19 typer.echo(f"Creating user: {name}")19 print(f"Creating user: {name}")202122if __name__ == "__main__":23 app()
modified:docs_src/commands/context/tutorial001.py+3 added-3 removed
3 unmodified lines
456@app.command()7def create(username: str):8 typer.echo(f"Creating user: {username}")8 print(f"Creating user: {username}")91011@app.command()12def delete(username: str):13 typer.echo(f"Deleting user: {username}")13 print(f"Deleting user: {username}")141516@app.callback()17def 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}")222324if __name__ == "__main__":25 app()
modified:docs_src/commands/context/tutorial002.py+3 added-3 removed
3 unmodified lines
456@app.command()7def create(username: str):8 typer.echo(f"Creating user: {username}")8 print(f"Creating user: {username}")91011@app.command()12def delete(username: str):13 typer.echo(f"Deleting user: {username}")13 print(f"Deleting user: {username}")141516@app.callback(invoke_without_command=True)17def main():18 """19 Manage users in the awesome CLI app.20 """21 typer.echo("Initializing database")21 print("Initializing database")222324if __name__ == "__main__":25 app()
modified:docs_src/commands/context/tutorial003.py+3 added-3 removed
3 unmodified lines
456@app.command()7def create(username: str):8 typer.echo(f"Creating user: {username}")8 print(f"Creating user: {username}")91011@app.command()12def delete(username: str):13 typer.echo(f"Deleting user: {username}")13 print(f"Deleting user: {username}")141516@app.callback(invoke_without_command=True)17def 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")232425if __name__ == "__main__":26 app()
modified:docs_src/commands/context/tutorial004.py+1 added-1 removed
6 unmodified lines
7 context_settings={"allow_extra_args": True, "ignore_unknown_options": True}8)9def 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}")121314if __name__ == "__main__":15 app()
modified:docs_src/commands/help/tutorial001.py+6 added-6 removed
6 unmodified lines
7def 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}")121314@app.command()15def delete(
9 unmodified lines
2526 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")323334@app.command()35def delete_all(
8 unmodified lines
4445 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")515253@app.command()54def init():55 """56 Initialize the users database.57 """58 typer.echo("Initializing user database")58 print("Initializing user database")596061if __name__ == "__main__":62 app()
modified:docs_src/commands/help/tutorial002.py+2 added-2 removed
6 unmodified lines
7def 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}")121314@app.command(help="Delete a user with USERNAME.")15def 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}")202122if __name__ == "__main__":23 app()
added:docs_src/commands/help/tutorial003.py+25 added
1import typer23app = typer.Typer()456@app.command()7def create(username: str):8 """9 Create a user.10 """11 print(f"Creating user: {username}")121314@app.command(deprecated=True)15def delete(username: str):16 """17 Delete a user.1819 This is deprecated and will stop being supported soon.20 """21 print(f"Deleting user: {username}")222324if __name__ == "__main__":25 app()
added:docs_src/commands/help/tutorial004.py+34 added
1import typer23app = typer.Typer(rich_markup_mode="rich")456@app.command()7def 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:1415 This requires a [underline]username[/underline].16 """17 print(f"Creating user: {username}")181920@app.command(help="[bold red]Delete[/bold red] a user with [italic]USERNAME[/italic].")21def 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}")313233if __name__ == "__main__":34 app()
added:docs_src/commands/help/tutorial005.py+34 added
1import typer23app = typer.Typer(rich_markup_mode="markdown")456@app.command()7def create(username: str = typer.Argument(..., help="The username to be **created**")):8 """9 **Create** a new *shinny* user. :sparkles:1011 * Create a username1213 * Show that the username is created1415 ---1617 Learn more at the [Typer docs website](https://typer.tiangolo.com)18 """19 print(f"Creating user: {username}")202122@app.command(help="**Delete** a user with *USERNAME*.")23def 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}")313233if __name__ == "__main__":34 app()
added:docs_src/commands/help/tutorial006.py+55 added
1import typer23app = typer.Typer(rich_markup_mode="rich")456@app.command()7def create(username: str):8 """9 [green]Create[/green] a new user. :sparkles:10 """11 print(f"Creating user: {username}")121314@app.command()15def delete(username: str):16 """17 [red]Delete[/red] a user. :fire:18 """19 print(f"Deleting user: {username}")202122@app.command(rich_help_panel="Utils and Configs")23def config(configuration: str):24 """25 [blue]Configure[/blue] the system. :wrench:26 """27 print(f"Configuring the system with: {configuration}")282930@app.command(rich_help_panel="Utils and Configs")31def sync():32 """33 [blue]Synchronize[/blue] the system or something fancy like that. :recycle:34 """35 print("Syncing the system")363738@app.command(rich_help_panel="Help and Others")39def help():40 """41 Get [yellow]help[/yellow] with the system. :question:42 """43 print("Opening help portal...")444546@app.command(rich_help_panel="Help and Others")47def report():48 """49 [yellow]Report[/yellow] an issue. :bug:50 """51 print("Please open a new issue online, not a direct message")525354if __name__ == "__main__":55 app()
added:docs_src/commands/help/tutorial007.py+39 added
1from typing import Union23import typer45app = typer.Typer(rich_markup_mode="rich")678@app.command()9def 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}")282930@app.command(rich_help_panel="Utils and Configs")31def config(configuration: str):32 """33 [blue]Configure[/blue] the system. :wrench:34 """35 print(f"Configuring the system with: {configuration}")363738if __name__ == "__main__":39 app()
added:docs_src/commands/help/tutorial008.py+15 added
1import typer23app = typer.Typer(rich_markup_mode="rich")456@app.command(epilog="Made with :heart: in [blue]Venus[/blue]")7def create(username: str):8 """9 [green]Create[/green] a new user. :sparkles:10 """11 print(f"Creating user: {username}")121314if __name__ == "__main__":15 app()
modified:docs_src/commands/index/tutorial001.py+1 added-1 removed
3 unmodified lines
456@app.command()7def main(name: str):8 typer.echo(f"Hello {name}")8 print(f"Hello {name}")91011if __name__ == "__main__":12 app()
modified:docs_src/commands/index/tutorial002.py+2 added-2 removed
3 unmodified lines
456@app.command()7def create():8 typer.echo("Creating user: Hiro Hamada")8 print("Creating user: Hiro Hamada")91011@app.command()12def delete():13 typer.echo("Deleting user: Hiro Hamada")13 print("Deleting user: Hiro Hamada")141516if __name__ == "__main__":17 app()
modified:docs_src/commands/name/tutorial001.py+2 added-2 removed
3 unmodified lines
456@app.command("create")7def cli_create_user(username: str):8 typer.echo(f"Creating user: {username}")8 print(f"Creating user: {username}")91011@app.command("delete")12def cli_delete_user(username: str):13 typer.echo(f"Deleting user: {username}")13 print(f"Deleting user: {username}")141516if __name__ == "__main__":17 app()
modified:docs_src/commands/one_or_multiple/tutorial001.py+1 added-1 removed
3 unmodified lines
456@app.command()7def create():8 typer.echo("Creating user: Hiro Hamada")8 print("Creating user: Hiro Hamada")91011@app.callback()12def callback():
5 unmodified lines
modified:docs_src/commands/one_or_multiple/tutorial002.py+1 added-1 removed
3 unmodified lines
456@app.command()7def create():8 typer.echo("Creating user: Hiro Hamada")8 print("Creating user: Hiro Hamada")91011@app.callback()12def callback():
9 unmodified lines
modified:docs_src/commands/options/tutorial001.py+6 added-6 removed
3 unmodified lines
456@app.command()7def create(username: str):8 typer.echo(f"Creating user: {username}")8 print(f"Creating user: {username}")91011@app.command()12def 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")202122@app.command()23def 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")303132@app.command()33def init():34 typer.echo("Initializing user database")34 print("Initializing user database")353637if __name__ == "__main__":38 app()
modified:docs_src/first_steps/tutorial001.py+1 added-1 removed
1import typer234def main():5 typer.echo("Hello World")5 print("Hello World")678if __name__ == "__main__":9 typer.run(main)
modified:docs_src/first_steps/tutorial002.py+1 added-1 removed
1import typer234def main(name: str):5 typer.echo(f"Hello {name}")5 print(f"Hello {name}")678if __name__ == "__main__":9 typer.run(main)
modified:docs_src/first_steps/tutorial003.py+1 added-1 removed
1import typer234def main(name: str, lastname: str):5 typer.echo(f"Hello {name} {lastname}")5 print(f"Hello {name} {lastname}")678if __name__ == "__main__":9 typer.run(main)
modified:docs_src/first_steps/tutorial004.py+2 added-2 removed
1 unmodified line
234def 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}")91011if __name__ == "__main__":12 typer.run(main)
modified:docs_src/first_steps/tutorial005.py+2 added-2 removed
1 unmodified line
234def 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}")91011if __name__ == "__main__":12 typer.run(main)
modified:docs_src/first_steps/tutorial006.py+2 added-2 removed
6 unmodified lines
78 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}")141516if __name__ == "__main__":17 typer.run(main)
modified:docs_src/launch/tutorial001.py+1 added-1 removed
1import typer234def main():5 typer.echo("Opening Typer's docs")5 print("Opening Typer's docs")6 typer.launch("https://typer.tiangolo.com")789if __name__ == "__main__":
1 unmodified line
modified:docs_src/launch/tutorial002.py+1 added-1 removed
11 unmodified lines
12 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)181920if __name__ == "__main__":
1 unmodified line
modified:docs_src/multiple_values/arguments_with_multiple_values/tutorial001.py+2 added-2 removed
5 unmodified lines
67def 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)121314if __name__ == "__main__":15 typer.run(main)
modified:docs_src/multiple_values/arguments_with_multiple_values/tutorial002.py+1 added-1 removed
7 unmodified lines
8 ("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}")131415if __name__ == "__main__":16 typer.run(main)
modified:docs_src/multiple_values/multiple_options/tutorial001.py+2 added-2 removed
3 unmodified lines
456def 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}")121314if __name__ == "__main__":15 typer.run(main)
modified:docs_src/multiple_values/multiple_options/tutorial002.py+1 added-1 removed
2 unmodified lines
3import typer456def main(number: List[float] = typer.Option([])):7 typer.echo(f"The sum is {sum(number)}")7 print(f"The sum is {sum(number)}")8910if __name__ == "__main__":11 typer.run(main)
modified:docs_src/multiple_values/options_with_multiple_values/tutorial001.py+3 added-3 removed
4 unmodified lines
56def 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!")141516if __name__ == "__main__":17 typer.run(main)
modified:docs_src/options/autocompletion/tutorial001.py+1 added-1 removed
1import typer234def main(name: str = typer.Option("World", help="The name to say hi to.")):5 typer.echo(f"Hello {name}")5 print(f"Hello {name}")678if __name__ == "__main__":9 typer.run(main)
modified:docs_src/options/autocompletion/tutorial002.py+1 added-1 removed
8 unmodified lines
9 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}")141516if __name__ == "__main__":17 typer.run(main)
modified:docs_src/options/autocompletion/tutorial003.py+1 added-1 removed
14 unmodified lines
15 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}")202122if __name__ == "__main__":23 typer.run(main)
modified:docs_src/options/autocompletion/tutorial004.py+1 added-1 removed
19 unmodified lines
20 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}")252627if __name__ == "__main__":28 typer.run(main)
modified:docs_src/options/autocompletion/tutorial005.py+1 added-1 removed
16 unmodified lines
17 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}")222324if __name__ == "__main__":25 typer.run(main)
modified:docs_src/options/autocompletion/tutorial006.py+1 added-1 removed
3 unmodified lines
456def 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}")91011if __name__ == "__main__":12 typer.run(main)
modified:docs_src/options/autocompletion/tutorial007.py+1 added-1 removed
20 unmodified lines
21 ["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}")262728if __name__ == "__main__":29 typer.run(main)
modified:docs_src/options/autocompletion/tutorial008.py+5 added-2 removed
1from typing import List23import typer4from rich.console import Console56valid_completion_items = [7 ("Camila", "The reader of books."),8 ("Carlos", "The writer of scripts."),9 ("Sebastian", "The type hints guy."),10]1112err_console = Console(stderr=True)131415def 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 lines
24 ["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}")293031if __name__ == "__main__":32 typer.run(main)
modified:docs_src/options/autocompletion/tutorial009.py+5 added-2 removed
1from typing import List23import typer4from rich.console import Console56valid_completion_items = [7 ("Camila", "The reader of books."),8 ("Carlos", "The writer of scripts."),9 ("Sebastian", "The type hints guy."),10]1112err_console = Console(stderr=True)131415def 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 lines
25 ["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}")303132if __name__ == "__main__":33 typer.run(main)
modified:docs_src/options/callback/tutorial001.py+1 added-1 removed
6 unmodified lines
7 return value8910def main(name: str = typer.Option(..., callback=name_callback)):11 typer.echo(f"Hello {name}")11 print(f"Hello {name}")121314if __name__ == "__main__":15 typer.run(main)
modified:docs_src/options/callback/tutorial002.py+2 added-2 removed
1import typer234def 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 value91011def main(name: str = typer.Option(..., callback=name_callback)):12 typer.echo(f"Hello {name}")12 print(f"Hello {name}")131415if __name__ == "__main__":16 typer.run(main)
modified:docs_src/options/callback/tutorial003.py+2 added-2 removed
2 unmodified lines
34def 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 value111213def main(name: str = typer.Option(..., callback=name_callback)):14 typer.echo(f"Hello {name}")14 print(f"Hello {name}")151617if __name__ == "__main__":18 typer.run(main)
modified:docs_src/options/callback/tutorial004.py+2 added-2 removed
2 unmodified lines
34def 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 value111213def main(name: str = typer.Option(..., callback=name_callback)):14 typer.echo(f"Hello {name}")14 print(f"Hello {name}")151617if __name__ == "__main__":18 typer.run(main)
modified:docs_src/options/help/tutorial001.py+2 added-2 removed
10 unmodified lines
1112 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}")181920if __name__ == "__main__":21 typer.run(main)
modified:docs_src/options/help/tutorial002.py+19 added-2 removed
1import typer234def main(fullname: str = typer.Option("Wade Wilson", show_default=False)):5 typer.echo(f"Hello {fullname}")4def 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.1617 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}")232425if __name__ == "__main__":26 typer.run(main)
added:docs_src/options/help/tutorial003.py+9 added
1import typer234def main(fullname: str = typer.Option("Wade Wilson", show_default=False)):5 print(f"Hello {fullname}")678if __name__ == "__main__":9 typer.run(main)
modified:docs_src/options/name/tutorial001.py+1 added-1 removed
1import typer234def main(user_name: str = typer.Option(..., "--name")):5 typer.echo(f"Hello {user_name}")5 print(f"Hello {user_name}")678if __name__ == "__main__":9 typer.run(main)
modified:docs_src/options/name/tutorial002.py+1 added-1 removed
1import typer234def main(user_name: str = typer.Option(..., "--name", "-n")):5 typer.echo(f"Hello {user_name}")5 print(f"Hello {user_name}")678if __name__ == "__main__":9 typer.run(main)
modified:docs_src/options/name/tutorial003.py+1 added-1 removed
1import typer234def main(user_name: str = typer.Option(..., "-n")):5 typer.echo(f"Hello {user_name}")5 print(f"Hello {user_name}")678if __name__ == "__main__":9 typer.run(main)
modified:docs_src/options/name/tutorial004.py+1 added-1 removed
1import typer234def main(user_name: str = typer.Option(..., "--user-name", "-n")):5 typer.echo(f"Hello {user_name}")5 print(f"Hello {user_name}")678if __name__ == "__main__":9 typer.run(main)
modified:docs_src/options/name/tutorial005.py+2 added-2 removed
4 unmodified lines
5 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}")121314if __name__ == "__main__":15 typer.run(main)
modified:docs_src/options/password/tutorial001.py+1 added-1 removed
2 unmodified lines
34def 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}")8910if __name__ == "__main__":11 typer.run(main)
modified:docs_src/options/password/tutorial002.py+2 added-2 removed
5 unmodified lines
6 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}")121314if __name__ == "__main__":15 typer.run(main)
modified:docs_src/options/prompt/tutorial001.py+1 added-1 removed
1import typer234def main(name: str, lastname: str = typer.Option(..., prompt=True)):5 typer.echo(f"Hello {name} {lastname}")5 print(f"Hello {name} {lastname}")678if __name__ == "__main__":9 typer.run(main)
modified:docs_src/options/prompt/tutorial002.py+1 added-1 removed
2 unmodified lines
34def 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}")8910if __name__ == "__main__":11 typer.run(main)
modified:docs_src/options/prompt/tutorial003.py+1 added-1 removed
1import typer234def 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}")678if __name__ == "__main__":9 typer.run(main)
modified:docs_src/options/required/tutorial001.py+1 added-1 removed
1import typer234def main(name: str, lastname: str = typer.Option(...)):5 typer.echo(f"Hello {name} {lastname}")5 print(f"Hello {name} {lastname}")678if __name__ == "__main__":9 typer.run(main)
modified:docs_src/options/version/tutorial001.py+2 added-2 removed
5 unmodified lines
678def 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()121314def main(
1 unmodified line
16 version: Optional[bool] = typer.Option(17 None, "--version", callback=version_callback18 ),19):20 typer.echo(f"Hello {name}")20 print(f"Hello {name}")212223if __name__ == "__main__":24 typer.run(main)
modified:docs_src/options/version/tutorial002.py+2 added-2 removed
5 unmodified lines
678def 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()121314def name_callback(name: str):
6 unmodified lines
21 version: Optional[bool] = typer.Option(22 None, "--version", callback=version_callback23 ),24):25 typer.echo(f"Hello {name}")25 print(f"Hello {name}")262728if __name__ == "__main__":29 typer.run(main)
modified:docs_src/options/version/tutorial003.py+2 added-2 removed
5 unmodified lines
678def 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()121314def name_callback(name: str):
7 unmodified lines
22 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}")272829if __name__ == "__main__":30 typer.run(main)
modified:docs_src/parameter_types/bool/tutorial001.py+2 added-2 removed
1 unmodified line
234def 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")91011if __name__ == "__main__":12 typer.run(main)
modified:docs_src/parameter_types/bool/tutorial002.py+3 added-3 removed
3 unmodified lines
456def 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!")131415if __name__ == "__main__":16 typer.run(main)
modified:docs_src/parameter_types/bool/tutorial003.py+2 added-2 removed
1 unmodified line
234def 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")91011if __name__ == "__main__":12 typer.run(main)
modified:docs_src/parameter_types/bool/tutorial004.py+2 added-2 removed
1 unmodified line
234def 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")91011if __name__ == "__main__":12 typer.run(main)
modified:docs_src/parameter_types/datetime/tutorial001.py+2 added-2 removed
2 unmodified lines
3import typer456def 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}")91011if __name__ == "__main__":12 typer.run(main)
modified:docs_src/parameter_types/datetime/tutorial002.py+1 added-1 removed
6 unmodified lines
7 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}")121314if __name__ == "__main__":15 typer.run(main)
modified:docs_src/parameter_types/enum/tutorial001.py+1 added-1 removed
8 unmodified lines
9 lstm = "lstm"101112def 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}")141516if __name__ == "__main__":17 typer.run(main)
modified:docs_src/parameter_types/enum/tutorial002.py+1 added-1 removed
10 unmodified lines
1112def 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}")161718if __name__ == "__main__":19 typer.run(main)
modified:docs_src/parameter_types/file/tutorial001.py+1 added-1 removed
1 unmodified line
234def main(config: typer.FileText = typer.Option(...)):5 for line in config:6 typer.echo(f"Config line: {line}")6 print(f"Config line: {line}")789if __name__ == "__main__":10 typer.run(main)
modified:docs_src/parameter_types/file/tutorial002.py+1 added-1 removed
1 unmodified line
234def main(config: typer.FileTextWrite = typer.Option(...)):5 config.write("Some config written by the app")6 typer.echo("Config written")6 print("Config written")789if __name__ == "__main__":10 typer.run(main)
modified:docs_src/parameter_types/file/tutorial003.py+1 added-1 removed
4 unmodified lines
5 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}")101112if __name__ == "__main__":13 typer.run(main)
modified:docs_src/parameter_types/file/tutorial004.py+1 added-1 removed
8 unmodified lines
9 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")141516if __name__ == "__main__":17 typer.run(main)
modified:docs_src/parameter_types/file/tutorial005.py+1 added-1 removed
1 unmodified line
234def 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")789if __name__ == "__main__":10 typer.run(main)
modified:docs_src/parameter_types/index/tutorial001.py+4 added-4 removed
1import typer234def 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)}")91011if __name__ == "__main__":12 typer.run(main)
modified:docs_src/parameter_types/number/tutorial001.py+3 added-3 removed
4 unmodified lines
5 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}")121314if __name__ == "__main__":15 typer.run(main)
modified:docs_src/parameter_types/number/tutorial002.py+3 added-3 removed
4 unmodified lines
5 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}")121314if __name__ == "__main__":15 typer.run(main)
modified:docs_src/parameter_types/number/tutorial003.py+1 added-1 removed
1import typer234def 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}")678if __name__ == "__main__":9 typer.run(main)
modified:docs_src/parameter_types/path/tutorial001.py+4 added-4 removed
4 unmodified lines
567def 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")181920if __name__ == "__main__":21 typer.run(main)
modified:docs_src/parameter_types/path/tutorial002.py+1 added-1 removed
13 unmodified lines
14 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}")192021if __name__ == "__main__":22 typer.run(main)
modified:docs_src/parameter_types/uuid/tutorial001.py+2 added-2 removed
2 unmodified lines
3import typer456def 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}")91011if __name__ == "__main__":12 typer.run(main)
modified:docs_src/printing/tutorial001.py+12 added-8 removed
1import typer2from rich import print34data = {5 "name": "Rick",6 "age": 42,7 "items": [{"name": "Portal Gun"}, {"name": "Plumbus"}],8 "active": True,9 "affiliation": None,10}114def 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)1213def main():14 print("Here's the data")15 print(data)161718if __name__ == "__main__":19 typer.run(main)
modified:docs_src/printing/tutorial002.py+3 added-2 removed
1import typer2from rich import print344def main(name: str):5 typer.secho(f"Welcome here {name}", fg=typer.colors.MAGENTA)5def main():6 print("[bold red]Alert![/bold red] [green]Portal gun[/green] shooting! :boom:")789if __name__ == "__main__":10 typer.run(main)
modified:docs_src/printing/tutorial003.py+8 added-1 removed
1import typer2from rich.console import Console3from rich.table import Table45console = Console()678def 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)131415if __name__ == "__main__":16 typer.run(main)
added:docs_src/printing/tutorial004.py+12 added
1import typer2from rich.console import Console34err_console = Console(stderr=True)567def main():8 err_console.print("Here is something written to standard error")91011if __name__ == "__main__":12 typer.run(main)
added:docs_src/printing/tutorial005.py+15 added
1import typer234def 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)121314if __name__ == "__main__":15 typer.run(main)
added:docs_src/printing/tutorial006.py+9 added
1import typer234def main(name: str):5 typer.secho(f"Welcome here {name}", fg=typer.colors.MAGENTA)678if __name__ == "__main__":9 typer.run(main)
modified:docs_src/progressbar/tutorial001.py+1 added-1 removed
8 unmodified lines
9 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.")141516if __name__ == "__main__":17 typer.run(main)
modified:docs_src/progressbar/tutorial002.py+1 added-1 removed
14 unmodified lines
15 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.")202122if __name__ == "__main__":23 typer.run(main)
modified:docs_src/progressbar/tutorial003.py+1 added-1 removed
8 unmodified lines
9 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.")141516if __name__ == "__main__":17 typer.run(main)
modified:docs_src/progressbar/tutorial004.py+1 added-1 removed
8 unmodified lines
9 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.")141516if __name__ == "__main__":17 typer.run(main)
modified:docs_src/prompt/tutorial001.py+1 added-1 removed
1 unmodified line
234def main():5 person_name = typer.prompt("What's your name?")6 typer.echo(f"Hello {person_name}")6 print(f"Hello {person_name}")789if __name__ == "__main__":10 typer.run(main)
modified:docs_src/prompt/tutorial002.py+2 added-2 removed
2 unmodified lines
34def 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!")101112if __name__ == "__main__":13 typer.run(main)
modified:docs_src/prompt/tutorial003.py+1 added-1 removed
1 unmodified line
234def main():5 delete = typer.confirm("Are you sure you want to delete it?", abort=True)6 typer.echo("Deleting it!")6 print("Deleting it!")789if __name__ == "__main__":10 typer.run(main)
modified:docs_src/subcommands/callback_override/tutorial001.py+2 added-2 removed
6 unmodified lines
789@users_app.callback()10def users_callback():11 typer.echo("Running a users command")11 print("Running a users command")121314@users_app.command()15def create(name: str):16 typer.echo(f"Creating user: {name}")16 print(f"Creating user: {name}")171819if __name__ == "__main__":20 app()
modified:docs_src/subcommands/callback_override/tutorial002.py+2 added-2 removed
2 unmodified lines
3app = typer.Typer()456def users_callback():7 typer.echo("Running a users command")7 print("Running a users command")8910users_app = typer.Typer(callback=users_callback)11app.add_typer(users_app, name="users")121314@users_app.command()15def create(name: str):16 typer.echo(f"Creating user: {name}")16 print(f"Creating user: {name}")171819if __name__ == "__main__":20 app()
modified:docs_src/subcommands/callback_override/tutorial003.py+3 added-3 removed
2 unmodified lines
3app = typer.Typer()456def default_callback():7 typer.echo("Running a users command")7 print("Running a users command")8910users_app = typer.Typer(callback=default_callback)11app.add_typer(users_app, name="users")121314@users_app.callback()15def user_callback():16 typer.echo("Callback override, running users command")16 print("Callback override, running users command")171819@users_app.command()20def create(name: str):21 typer.echo(f"Creating user: {name}")21 print(f"Creating user: {name}")222324if __name__ == "__main__":25 app()
modified:docs_src/subcommands/callback_override/tutorial004.py+4 added-4 removed
2 unmodified lines
3app = typer.Typer()456def default_callback():7 typer.echo("Running a users command")7 print("Running a users command")8910users_app = typer.Typer(callback=default_callback)111213def 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")151617app.add_typer(users_app, name="users", callback=callback_for_add_typer)181920@users_app.callback()21def user_callback():22 typer.echo("Callback override, running users command")22 print("Callback override, running users command")232425@users_app.command()26def create(name: str):27 typer.echo(f"Creating user: {name}")27 print(f"Creating user: {name}")282930if __name__ == "__main__":31 app()
modified:docs_src/subcommands/name_help/tutorial001.py+1 added-1 removed
6 unmodified lines
789@users_app.command()10def create(name: str):11 typer.echo(f"Creating user: {name}")11 print(f"Creating user: {name}")121314if __name__ == "__main__":15 app()
modified:docs_src/subcommands/name_help/tutorial002.py+1 added-1 removed
13 unmodified lines
141516@users_app.command()17def create(name: str):18 typer.echo(f"Creating user: {name}")18 print(f"Creating user: {name}")192021if __name__ == "__main__":22 app()
modified:docs_src/subcommands/name_help/tutorial003.py+1 added-1 removed
13 unmodified lines
141516@users_app.command()17def create(name: str):18 typer.echo(f"Creating user: {name}")18 print(f"Creating user: {name}")192021if __name__ == "__main__":22 app()
modified:docs_src/subcommands/name_help/tutorial004.py+1 added-1 removed
20 unmodified lines
212223@users_app.command()24def create(name: str):25 typer.echo(f"Creating user: {name}")25 print(f"Creating user: {name}")262728if __name__ == "__main__":29 app()
modified:docs_src/subcommands/name_help/tutorial005.py+1 added-1 removed
28 unmodified lines
293031@users_app.command()32def create(name: str):33 typer.echo(f"Creating user: {name}")33 print(f"Creating user: {name}")343536if __name__ == "__main__":37 app()
modified:docs_src/subcommands/name_help/tutorial006.py+1 added-1 removed
28 unmodified lines
293031@users_app.command()32def create(name: str):33 typer.echo(f"Creating user: {name}")33 print(f"Creating user: {name}")343536if __name__ == "__main__":37 app()
modified:docs_src/subcommands/name_help/tutorial007.py+1 added-1 removed
28 unmodified lines
293031@users_app.command()32def create(name: str):33 typer.echo(f"Creating user: {name}")33 print(f"Creating user: {name}")343536if __name__ == "__main__":37 app()
modified:docs_src/subcommands/name_help/tutorial008.py+1 added-1 removed
33 unmodified lines
343536@users_app.command()37def create(name: str):38 typer.echo(f"Creating user: {name}")38 print(f"Creating user: {name}")394041if __name__ == "__main__":42 app()
modified:docs_src/subcommands/tutorial001/items.py+3 added-3 removed
3 unmodified lines
456@app.command()7def create(item: str):8 typer.echo(f"Creating item: {item}")8 print(f"Creating item: {item}")91011@app.command()12def delete(item: str):13 typer.echo(f"Deleting item: {item}")13 print(f"Deleting item: {item}")141516@app.command()17def sell(item: str):18 typer.echo(f"Selling item: {item}")18 print(f"Selling item: {item}")192021if __name__ == "__main__":22 app()
modified:docs_src/subcommands/tutorial001/users.py+2 added-2 removed
3 unmodified lines
456@app.command()7def create(user_name: str):8 typer.echo(f"Creating user: {user_name}")8 print(f"Creating user: {user_name}")91011@app.command()12def delete(user_name: str):13 typer.echo(f"Deleting user: {user_name}")13 print(f"Deleting user: {user_name}")141516if __name__ == "__main__":17 app()
modified:docs_src/subcommands/tutorial002/main.py+5 added-5 removed
7 unmodified lines
8910@items_app.command("create")11def items_create(item: str):12 typer.echo(f"Creating item: {item}")12 print(f"Creating item: {item}")131415@items_app.command("delete")16def items_delete(item: str):17 typer.echo(f"Deleting item: {item}")17 print(f"Deleting item: {item}")181920@items_app.command("sell")21def items_sell(item: str):22 typer.echo(f"Selling item: {item}")22 print(f"Selling item: {item}")232425@users_app.command("create")26def users_create(user_name: str):27 typer.echo(f"Creating user: {user_name}")27 print(f"Creating user: {user_name}")282930@users_app.command("delete")31def users_delete(user_name: str):32 typer.echo(f"Deleting user: {user_name}")32 print(f"Deleting user: {user_name}")333435if __name__ == "__main__":36 app()
modified:docs_src/subcommands/tutorial003/items.py+3 added-3 removed
3 unmodified lines
456@app.command()7def create(item: str):8 typer.echo(f"Creating item: {item}")8 print(f"Creating item: {item}")91011@app.command()12def delete(item: str):13 typer.echo(f"Deleting item: {item}")13 print(f"Deleting item: {item}")141516@app.command()17def sell(item: str):18 typer.echo(f"Selling item: {item}")18 print(f"Selling item: {item}")192021if __name__ == "__main__":22 app()
modified:docs_src/subcommands/tutorial003/reigns.py+2 added-2 removed
3 unmodified lines
456@app.command()7def conquer(name: str):8 typer.echo(f"Conquering reign: {name}")8 print(f"Conquering reign: {name}")91011@app.command()12def destroy(name: str):13 typer.echo(f"Destroying reign: {name}")13 print(f"Destroying reign: {name}")141516if __name__ == "__main__":17 app()
modified:docs_src/subcommands/tutorial003/towns.py+2 added-2 removed
3 unmodified lines
456@app.command()7def found(name: str):8 typer.echo(f"Founding town: {name}")8 print(f"Founding town: {name}")91011@app.command()12def burn(name: str):13 typer.echo(f"Burning town: {name}")13 print(f"Burning town: {name}")141516if __name__ == "__main__":17 app()
modified:docs_src/subcommands/tutorial003/users.py+2 added-2 removed
3 unmodified lines
456@app.command()7def create(user_name: str):8 typer.echo(f"Creating user: {user_name}")8 print(f"Creating user: {user_name}")91011@app.command()12def delete(user_name: str):13 typer.echo(f"Deleting user: {user_name}")13 print(f"Deleting user: {user_name}")141516if __name__ == "__main__":17 app()
modified:docs_src/terminating/tutorial001.py+3 added-3 removed
3 unmodified lines
456def 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}")121314def 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}")171819def main(username: str):20 maybe_create_user(username=username)
5 unmodified lines
modified:docs_src/terminating/tutorial002.py+2 added-2 removed
1 unmodified line
234def 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}")91011if __name__ == "__main__":12 typer.run(main)
modified:docs_src/terminating/tutorial003.py+2 added-2 removed
1 unmodified line
234def 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}")91011if __name__ == "__main__":12 typer.run(main)
modified:docs_src/testing/app01/main.py+2 added-2 removed
5 unmodified lines
678@app.command()9def 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}")131415if __name__ == "__main__":16 app()
modified:docs_src/testing/app02/main.py+1 added-1 removed
3 unmodified lines
456@app.command()7def 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}")91011if __name__ == "__main__":12 app()
modified:docs_src/testing/app03/main.py+1 added-1 removed
1import typer234def main(name: str = "World"):5 typer.echo(f"Hello {name}")5 print(f"Hello {name}")678if __name__ == "__main__":9 typer.run(main)
modified:docs_src/using_click/tutorial003.py+1 added-1 removed
7 unmodified lines
8def 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")131415@app.callback()16def callback():
18 unmodified lines
modified:docs_src/using_click/tutorial004.py+1 added-1 removed
23 unmodified lines
24def 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")293031typer_click_object = typer.main.get_command(app)32
4 unmodified lines
modified:scripts/test.sh+4 added
1 unmodified line
23set -e4set -x56# For tests, a large terminal width7export TERMINAL_WIDTH=30008# Force disable terminal for tests inside of pytest, takes precedence over GITHUB_ACTIONS env var9export _TYPER_FORCE_DISABLE_TERMINAL=110bash ./scripts/test-files.sh11# Use xdist-pytest --forked to ensure modified sys.path to import relative modules in examples keeps working12pytest --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 lines
21):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}")262728if __name__ == "__main__":29 app()
modified:tests/assets/completion_no_types_order.py+1 added-1 removed
14 unmodified lines
151617@app.command()18def main(name: str = typer.Option("World", autocompletion=complete)):19 typer.echo(f"Hello {name}")19 print(f"Hello {name}")202122if __name__ == "__main__":23 app()
modified:tests/assets/completion_no_types.py+1 added-1 removed
14 unmodified lines
151617@app.command()18def main(name: str = typer.Option("World", autocompletion=complete)):19 typer.echo(f"Hello {name}")19 print(f"Hello {name}")202122if __name__ == "__main__":23 app()
modified:tests/test_compat/test_option_get_help.py+14 added
1import os2import subprocess34import typer.core5from typer.testing import CliRunner67from tests.assets import compat_click7_8 as mod8
9 unmodified lines
18 assert "TEST_LASTNAME" in result.output19 assert "(dynamic)" in result.output202122def 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 = rich333435def 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.output
17 unmodified lines
modified:tests/test_completion/test_completion_install.py+2 added-2 removed
26 unmodified lines
27 },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 )343536def test_completion_install_bash():
121 unmodified lines
modified:tests/test_completion/test_completion_show.py+2 added-2 removed
16 unmodified lines
17 },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 )242526def test_completion_show_bash():
81 unmodified lines
modified:tests/test_tutorial/test_arguments/test_default/test_tutorial001.py+1 added-1 removed
13 unmodified lines
14def 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.output202122def test_call_no_arg():
19 unmodified lines
modified:tests/test_tutorial/test_arguments/test_default/test_tutorial002.py+1 added-1 removed
13 unmodified lines
14def 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.output202122def test_call_no_arg():
21 unmodified lines
modified:tests/test_tutorial/test_arguments/test_envvar/test_tutorial001.py+16 added-2 removed
1import subprocess23import typer4import typer.core5from typer.testing import CliRunner67from docs_src.arguments.envvar import tutorial001 as mod8
6 unmodified lines
15def 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.output222324def 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 = rich343536def test_call_arg():37 result = runner.invoke(app, ["Wednesday"])38 assert result.exit_code == 039 assert "Hello Mr. Wednesday" in result.output
22 unmodified lines
modified:tests/test_tutorial/test_arguments/test_envvar/test_tutorial002.py+3 added-2 removed
13 unmodified lines
14def 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.output212223def test_call_arg():24 result = runner.invoke(app, ["Wednesday"])
24 unmodified lines
modified:tests/test_tutorial/test_arguments/test_envvar/test_tutorial003.py+3 added-3 removed
13 unmodified lines
14def 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.output212223def test_call_arg():24 result = runner.invoke(app, ["Wednesday"])
24 unmodified lines
modified:tests/test_tutorial/test_arguments/test_help/test_tutorial001.py+15 added-1 removed
1import subprocess23import typer4import typer.core5from typer.testing import CliRunner67from docs_src.arguments.help import tutorial001 as mod8
6 unmodified lines
15def 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.output232425def 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 = rich363738def test_call_arg():39 result = runner.invoke(app, ["Camila"])40 assert result.exit_code == 041 assert "Hello Camila" in result.output
10 unmodified lines
modified:tests/test_tutorial/test_arguments/test_help/test_tutorial002.py+1 added-1 removed
14 unmodified lines
15 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 lines
modified:tests/test_tutorial/test_arguments/test_help/test_tutorial003.py+1 added-1 removed
14 unmodified lines
15 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 lines
modified:tests/test_tutorial/test_arguments/test_help/test_tutorial004.py+1 added-1 removed
14 unmodified lines
15 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 lines
modified:tests/test_tutorial/test_arguments/test_help/test_tutorial005.py+1 added-1 removed
13 unmodified lines
14def 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.output2122
14 unmodified lines
modified:tests/test_tutorial/test_arguments/test_help/test_tutorial006.py+1 added-1 removed
13 unmodified lines
14def 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.output2122
14 unmodified lines
modified:tests/test_tutorial/test_arguments/test_help/test_tutorial007.py+3 added-3 removed
1import subprocess23import typer4import typer.core5from typer.testing import CliRunner67from docs_src.arguments.help import tutorial007 as mod8
5 unmodified lines
1415def 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.output212223def test_call_arg():24 result = runner.invoke(app, ["Camila"])
12 unmodified lines
added:tests/test_tutorial/test_arguments/test_help/test_tutorial008.py+49 added
1import subprocess23import typer4import typer.core5from typer.testing import CliRunner67from docs_src.arguments.help import tutorial008 as mod89runner = CliRunner()1011app = typer.Typer()12app.command()(mod.main)131415def 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.output222324def 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 = rich343536def test_call_arg():37 result = runner.invoke(app, ["Camila"])38 assert result.exit_code == 039 assert "Hello Camila" in result.output404142def 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.stdout
modified:tests/test_tutorial/test_arguments/test_optional/test_tutorial001.py+18 added-1 removed
1import subprocess23import typer4import typer.core5from typer.testing import CliRunner67from docs_src.arguments.optional import tutorial001 as mod8
5 unmodified lines
1415def 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.output192021def test_call_no_arg_standalone():22 # Mainly for coverage23 result = runner.invoke(app, standalone_mode=False)24 assert result.exit_code != 0252627def 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 = rich353637def test_call_arg():38 result = runner.invoke(app, ["Camila"])39 assert result.exit_code == 040 assert "Hello Camila" in result.output
10 unmodified lines
modified:tests/test_tutorial/test_commands/test_callback/test_tutorial001.py+16 added-3 removed
1import subprocess23import typer.core4from typer.testing import CliRunner56from docs_src.commands.callback import tutorial001 as mod7
5 unmodified lines
13def 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.output192021def 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 = rich303132def test_create():33 result = runner.invoke(app, ["create", "Camila"])34 assert result.exit_code == 035 assert "Creating user: Camila" in result.output
27 unmodified lines
63 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 )707172def test_script():
7 unmodified lines
modified:tests/test_tutorial/test_commands/test_help/test_tutorial001.py+4 added-2 removed
33 unmodified lines
34 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.output414243def test_help_delete_all():
2 unmodified lines
46 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.output535455def test_help_init():
70 unmodified lines
added:tests/test_tutorial/test_commands/test_help/test_tutorial003.py+44 added
1import subprocess23from typer.testing import CliRunner45from docs_src.commands.help import tutorial003 as mod67app = mod.app89runner = CliRunner()101112def 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.output202122def 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.output272829def 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 == 0353637def 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.stdout
added:tests/test_tutorial/test_commands/test_help/test_tutorial004.py+59 added
1import subprocess23from typer.testing import CliRunner45from docs_src.commands.help import tutorial004 as mod67app = mod.app89runner = CliRunner()101112def 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.output212223def 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.output293031def 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.output383940def test_create():41 result = runner.invoke(app, ["create", "Camila"])42 assert result.exit_code == 043 assert "Creating user: Camila" in result.output444546def test_delete():47 result = runner.invoke(app, ["delete", "Camila"])48 assert result.exit_code == 049 assert "Deleting user: Camila" in result.output505152def 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.stdout
added:tests/test_tutorial/test_commands/test_help/test_tutorial005.py+60 added
1import subprocess23from typer.testing import CliRunner45from docs_src.commands.help import tutorial005 as mod67app = mod.app89runner = CliRunner()101112def 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.output212223def 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.output303132def 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.output394041def test_create():42 result = runner.invoke(app, ["create", "Camila"])43 assert result.exit_code == 044 assert "Creating user: Camila" in result.output454647def test_delete():48 result = runner.invoke(app, ["delete", "Camila"])49 assert result.exit_code == 050 assert "Deleting user: Camila" in result.output515253def 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.stdout
added:tests/test_tutorial/test_commands/test_help/test_tutorial006.py+51 added
1import subprocess23from typer.testing import CliRunner45from docs_src.commands.help import tutorial006 as mod67app = mod.app89runner = CliRunner()101112def 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.output262728def 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 == 0424344def 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.stdout
added:tests/test_tutorial/test_commands/test_help/test_tutorial007.py+55 added
1import subprocess23from typer.testing import CliRunner45from docs_src.commands.help import tutorial007 as mod67app = mod.app89runner = CliRunner()101112def 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.output202122def 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.output383940def 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 == 0464748def 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.stdout
added:tests/test_tutorial/test_commands/test_help/test_tutorial008.py+32 added
1import subprocess23from typer.testing import CliRunner45from docs_src.commands.help import tutorial008 as mod67app = mod.app89runner = CliRunner()101112def 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.output171819def test_call():20 # Mainly for coverage21 result = runner.invoke(app, ["Morty"])22 assert result.exit_code == 0232425def 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.stdout
modified:tests/test_tutorial/test_commands/test_index/test_tutorial001.py+1 added-1 removed
10 unmodified lines
1112def 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.output161718def test_arg():19 result = runner.invoke(app, ["Camila"])
12 unmodified lines
modified:tests/test_tutorial/test_commands/test_index/test_tutorial002.py+1 added-1 removed
11 unmodified lines
12def 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.output1920
20 unmodified lines
modified:tests/test_tutorial/test_commands/test_name/test_tutorial001.py+1 added-1 removed
10 unmodified lines
1112def 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.output1819
20 unmodified lines
modified:tests/test_tutorial/test_commands/test_one_or_multiple/test_tutorial001.py+1 added-1 removed
10 unmodified lines
1112def 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.output171819def test_command():
13 unmodified lines
modified:tests/test_tutorial/test_commands/test_one_or_multiple/test_tutorial002.py+1 added-1 removed
12 unmodified lines
13 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.output192021def test_command():
13 unmodified lines
modified:tests/test_tutorial/test_commands/test_options/test_tutorial001.py+1 added-1 removed
10 unmodified lines
1112def 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.output
77 unmodified lines
modified:tests/test_tutorial/test_first_steps/test_tutorial002.py+1 added-1 removed
12 unmodified lines
1314def 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.output181920def test_2():21 result = runner.invoke(app, ["Camila"])
12 unmodified lines
modified:tests/test_tutorial/test_first_steps/test_tutorial003.py+1 added-1 removed
12 unmodified lines
1314def 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.output181920def test_2():21 result = runner.invoke(app, ["Camila", "Gutiérrez"])
12 unmodified lines
modified:tests/test_tutorial/test_first_steps/test_tutorial004.py+7 added-4 removed
12 unmodified lines
1314def 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.output242526def test_1():27 result = runner.invoke(app, ["Camila", "Gutiérrez"])
30 unmodified lines
modified:tests/test_tutorial/test_first_steps/test_tutorial005.py+7 added-4 removed
12 unmodified lines
1314def 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.output242526def test_1():27 result = runner.invoke(app, ["Camila"])
30 unmodified lines
modified:tests/test_tutorial/test_multiple_values/test_arguments_with_multiple_values/test_tutorial002.py+3 added-3 removed
12 unmodified lines
13def 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.output192021def test_defaults():
9 unmodified lines
31 assert result.exit_code != 032 # TODO: when deprecating Click 7, remove second option3334 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 )383940def test_valid_args():
15 unmodified lines
modified:tests/test_tutorial/test_multiple_values/test_multiple_options/test_tutorial001.py+1 added-1 removed
12 unmodified lines
13def 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.output181920def test_1_user():21 result = runner.invoke(app, ["--user", "Camila"])
22 unmodified lines
modified:tests/test_tutorial/test_multiple_values/test_options_with_multiple_values/test_tutorial001.py+3 added-3 removed
12 unmodified lines
13def 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.output181920def test_user_1():21 result = runner.invoke(app, ["--user", "Camila", "50", "yes"])
14 unmodified lines
36 assert result.exit_code != 037 # TODO: when deprecating Click 7, remove second option3839 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 )434445def test_script():
7 unmodified lines
modified:tests/test_tutorial/test_options/test_callback/test_tutorial001.py+1 added-1 removed
18 unmodified lines
1920def 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.output242526def test_script():27 result = subprocess.run(
6 unmodified lines
modified:tests/test_tutorial/test_options/test_callback/test_tutorial003.py+1 added-1 removed
20 unmodified lines
2122def 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.output262728def test_script():29 result = subprocess.run(
23 unmodified lines
modified:tests/test_tutorial/test_options/test_callback/test_tutorial004.py+1 added-1 removed
20 unmodified lines
2122def 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.output262728def test_script():29 result = subprocess.run(
23 unmodified lines
modified:tests/test_tutorial/test_options/test_help/test_tutorial002.py+14 added-4 removed
10 unmodified lines
11app.command()(mod.main)121314def 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.output181920def test_formal():21 result = runner.invoke(app, ["World", "--formal"])22 assert result.exit_code == 023 assert "Good day Ms. World" in result.output242526def 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.output353637def test_script():38 result = subprocess.run(
6 unmodified lines
added:tests/test_tutorial/test_options/test_help/test_tutorial003.py+35 added
1import subprocess23import typer4from typer.testing import CliRunner56from docs_src.options.help import tutorial003 as mod78runner = CliRunner()910app = typer.Typer()11app.command()(mod.main)121314def test_call():15 result = runner.invoke(app)16 assert result.exit_code == 017 assert "Hello Wade Wilson" in result.output181920def 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.output262728def 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.stdout
modified:tests/test_tutorial/test_options/test_name/test_tutorial001.py+2 added-1 removed
12 unmodified lines
1314def 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.output202122def test_call():
13 unmodified lines
modified:tests/test_tutorial/test_options/test_name/test_tutorial002.py+3 added-1 removed
12 unmodified lines
1314def 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.output212223def test_call():
19 unmodified lines
modified:tests/test_tutorial/test_options/test_name/test_tutorial003.py+2 added-1 removed
12 unmodified lines
1314def 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.output2122
14 unmodified lines
modified:tests/test_tutorial/test_options/test_name/test_tutorial004.py+3 added-1 removed
12 unmodified lines
1314def 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.output212223def test_call():
19 unmodified lines
modified:tests/test_tutorial/test_options/test_name/test_tutorial005.py+5 added-2 removed
12 unmodified lines
1314def 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.output222324def test_call():25 result = runner.invoke(app, ["-n", "Camila"])
29 unmodified lines
modified:tests/test_tutorial/test_options/test_prompt/test_tutorial001.py+2 added-1 removed
25 unmodified lines
2627def 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.output333435def test_script():
7 unmodified lines
modified:tests/test_tutorial/test_options/test_prompt/test_tutorial002.py+2 added-1 removed
25 unmodified lines
2627def 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.output333435def test_script():
7 unmodified lines
modified:tests/test_tutorial/test_options/test_prompt/test_tutorial003.py+2 added-1 removed
39 unmodified lines
4041def 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.output474849def test_script():
7 unmodified lines
modified:tests/test_tutorial/test_options/test_required/test_tutorial002.py+15 added-2 removed
1import subprocess23import typer4import typer.core5from typer.testing import CliRunner67from docs_src.options.required import tutorial001 as mod8
5 unmodified lines
1415def 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.output192021def test_option_lastname():22 result = runner.invoke(app, ["Camila", "--lastname", "Gutiérrez"])
3 unmodified lines
2627def 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.output333435def 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 = rich444546def test_script():47 result = subprocess.run(48 ["coverage", "run", mod.__file__, "--help"],49 stdout=subprocess.PIPE,
4 unmodified lines
modified:tests/test_tutorial/test_options/test_version/test_tutorial003.py+1 added-1 removed
19 unmodified lines
2021def 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.output252627def test_3():28 result = runner.invoke(app, ["--name", "Camila"])
29 unmodified lines
modified:tests/test_tutorial/test_parameter_types/test_bool/test_tutorial001.py+2 added-2 removed
34 unmodified lines
35 assert result.exit_code != 036 # TODO: when deprecating Click 7, remove second option3738 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 )424344def test_script():
7 unmodified lines
modified:tests/test_tutorial/test_parameter_types/test_bool/test_tutorial002.py+16 added-3 removed
1import subprocess23import typer4import typer.core5from typer.testing import CliRunner67from docs_src.parameter_types.bool import tutorial002 as mod8
5 unmodified lines
1415def 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.output212223def 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 = rich323334def test_main():35 result = runner.invoke(app)36 assert result.exit_code == 037 assert "I don't know what you want yet" in result.output
16 unmodified lines
54 assert result.exit_code != 055 # TODO: when deprecating Click 7, remove second option5657 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 )616263def test_script():
7 unmodified lines
modified:tests/test_tutorial/test_parameter_types/test_bool/test_tutorial003.py+4 added-1 removed
12 unmodified lines
1314def 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.output212223def test_force():24 result = runner.invoke(app, ["-f"])
18 unmodified lines
modified:tests/test_tutorial/test_parameter_types/test_bool/test_tutorial004.py+2 added-1 removed
12 unmodified lines
1314def 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.output192021def test_main():22 result = runner.invoke(app)
24 unmodified lines
modified:tests/test_tutorial/test_parameter_types/test_datetime/test_tutorial001.py+9 added-4 removed
25 unmodified lines
2627def 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.output424344def test_script():45 result = subprocess.run(
6 unmodified lines
modified:tests/test_tutorial/test_parameter_types/test_enum/test_tutorial001.py+7 added-4 removed
12 unmodified lines
1314def 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.output192021def test_main():22 result = runner.invoke(app, ["--network", "conv"])
6 unmodified lines
29 assert result.exit_code != 030 # TODO: when deprecating Click 7, remove second option3132 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.output404142def test_script():43 result = subprocess.run(
6 unmodified lines
modified:tests/test_tutorial/test_parameter_types/test_index/test_tutorial001.py+6 added-6 removed
12 unmodified lines
1314def 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.output212223def test_params():24 result = runner.invoke(
11 unmodified lines
36 assert result.exit_code != 037 # TODO: when deprecating Click 7, remove second option3839 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 )434445def test_script():
7 unmodified lines
modified:tests/test_tutorial/test_parameter_types/test_number/test_tutorial001.py+23 added-9 removed
1import subprocess23import typer4import typer.core5from typer.testing import CliRunner67from docs_src.parameter_types.number import tutorial001 as mod8
5 unmodified lines
1415def 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.output222324def 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 = rich343536def test_params():37 result = runner.invoke(app, ["5", "--age", "20", "--score", "90"])38 assert result.exit_code == 039 assert "ID is 5" in result.output
6 unmodified lines
46 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 )5657
2 unmodified lines
60 assert result.exit_code != 061 # TODO: when deprecating Click 7, remove second option6263 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 )686970def test_invalid_score():
1 unmodified line
72 assert result.exit_code != 073 # TODO: when deprecating Click 7, remove second option7475 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 )8182
16 unmodified lines
modified:tests/test_tutorial/test_parameter_types/test_number/test_tutorial002.py+2 added-3 removed
15 unmodified lines
16 assert result.exit_code != 017 # TODO: when deprecating Click 7, remove second option1819 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 )242526def test_clamped():
15 unmodified lines
modified:tests/test_tutorial/test_parameter_types/test_path/test_tutorial001.py+1 added-1 removed
15 unmodified lines
16 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.output212223def test_not_exists(tmpdir):24 config_file = Path(tmpdir) / "config.txt"
30 unmodified lines
modified:tests/test_tutorial/test_parameter_types/test_path/test_tutorial002.py+2 added-5 removed
16 unmodified lines
17 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.output232425def test_exists(tmpdir):
7 unmodified lines
3334def 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.output383940def test_script():41 result = subprocess.run(
6 unmodified lines
modified:tests/test_tutorial/test_parameter_types/test_uuid/test_tutorial001.py+2 added-2 removed
22 unmodified lines
23 assert result.exit_code != 024 # TODO: when deprecating Click 7, remove second option2526 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 )3233
8 unmodified lines
modified:tests/test_tutorial/test_prompt/test_tutorial002.py+1 added-1 removed
21 unmodified lines
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 "Not deleting" in result.output26 assert "Aborted!" in result.output26 assert "Aborted" in result.output272829def test_script():30 result = subprocess.run(
6 unmodified lines
modified:tests/test_tutorial/test_prompt/test_tutorial003.py+1 added-1 removed
20 unmodified lines
21def 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.output262728def test_script():29 result = subprocess.run(
6 unmodified lines
modified:tests/test_tutorial/test_subcommands/test_name_help/test_tutorial001.py+1 added-1 removed
10 unmodified lines
1112def 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.output1819
20 unmodified lines
modified:tests/test_tutorial/test_subcommands/test_name_help/test_tutorial002.py+1 added-1 removed
10 unmodified lines
1112def 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.output1819
20 unmodified lines
modified:tests/test_tutorial/test_subcommands/test_name_help/test_tutorial003.py+1 added-1 removed
10 unmodified lines
1112def 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.output1819
20 unmodified lines
modified:tests/test_tutorial/test_subcommands/test_name_help/test_tutorial004.py+1 added-1 removed
10 unmodified lines
1112def 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.output1819
20 unmodified lines
modified:tests/test_tutorial/test_subcommands/test_name_help/test_tutorial005.py+1 added-1 removed
10 unmodified lines
1112def 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.output1819
20 unmodified lines
modified:tests/test_tutorial/test_subcommands/test_name_help/test_tutorial006.py+1 added-1 removed
10 unmodified lines
1112def 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.output1819
20 unmodified lines
modified:tests/test_tutorial/test_subcommands/test_name_help/test_tutorial007.py+1 added-1 removed
10 unmodified lines
1112def 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.output1819
20 unmodified lines
modified:tests/test_tutorial/test_subcommands/test_name_help/test_tutorial008.py+1 added-1 removed
10 unmodified lines
1112def 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.output1819
20 unmodified lines
modified:tests/test_tutorial/test_subcommands/test_tutorial001.py+3 added-3 removed
24 unmodified lines
25def 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.output323334def 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 lines
62def 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 lines
modified:tests/test_tutorial/test_subcommands/test_tutorial002.py+3 added-3 removed
10 unmodified lines
11def 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.output181920def 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 lines
48def 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 lines
modified:tests/test_tutorial/test_subcommands/test_tutorial003.py+6 added-6 removed
24 unmodified lines
25def 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 line
35def 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 lines
63def 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 lines
85def 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.output929394def 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.output101102
12 unmodified lines
115def 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.output122123
23 unmodified lines
modified:tests/test_tutorial/test_terminating/test_tutorial001.py+8 added
23 unmodified lines
24 assert "The user already exists" in result.output25 assert "Notification sent for new user" not in result.output262728def 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.output343536def test_script():37 result = subprocess.run(38 ["coverage", "run", mod.__file__, "--help"],39 stdout=subprocess.PIPE,
4 unmodified lines
modified:tests/test_tutorial/test_terminating/test_tutorial003.py+19 added-1 removed
1import subprocess23import typer4import typer.core5from typer.testing import CliRunner67from docs_src.terminating import tutorial003 as mod8
12 unmodified lines
21def 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.output262728def test_root_no_standalone():29 # Mainly for coverage30 result = runner.invoke(app, ["root"], standalone_mode=False)31 assert result.exit_code == 1323334def 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 = rich434445def test_script():46 result = subprocess.run(47 ["coverage", "run", mod.__file__, "--help"],48 stdout=subprocess.PIPE,
4 unmodified lines
modified:tests/test_tutorial/test_using_click/test_tutorial003.py+1 added-1 removed
8 unmodified lines
910def 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.stdout141516def test_typer():17 result = runner.invoke(mod.typer_click_object, ["top"])
16 unmodified lines
added:tests/test_exit_errors.py+45 added
1import errno23import typer4import typer.completion5from typer.testing import CliRunner67runner = CliRunner()8910def test_eoferror():11 # Mainly for coverage/completeness12 app = typer.Typer()1314 @app.command()15 def main():16 raise EOFError()1718 result = runner.invoke(app)19 assert result.exit_code == 1202122def test_oserror():23 # Mainly for coverage/completeness24 app = typer.Typer()2526 @app.command()27 def main():28 e = OSError()29 e.errno = errno.EPIPE30 raise e3132 result = runner.invoke(app)33 assert result.exit_code == 1343536def test_oserror_no_epipe():37 # Mainly for coverage/completeness38 app = typer.Typer()3940 @app.command()41 def main():42 raise OSError()4344 result = runner.invoke(app)45 assert result.exit_code == 1
modified:tests/test_others.py+15 added-17 removed
30 unmodified lines
31 app = typer.Typer()3233 @app.command()34 def main():35 typer.echo("Hello World")35 print("Hello World")3637 with mock.patch.object(38 shellingham, "detect_shell", return_value=("xshell", "/usr/bin/xshell")39 ):
23 unmodified lines
63def test_callback_2_untyped_parameters():64 app = typer.Typer()6566 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}")6970 @app.command()71 def main(name: str = typer.Option(..., callback=name_callback)):72 typer.echo("Hello World")72 print("Hello World")7374 result = runner.invoke(app, ["--name", "Camila"])75 assert "info name is: main" in result.stdout76 assert "value is: Camila" in result.stdout
2 unmodified lines
79def test_callback_3_untyped_parameters():80 app = typer.Typer()8182 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}")8687 @app.command()88 def main(name: str = typer.Option(..., callback=name_callback)):89 typer.echo("Hello World")89 print("Hello World")9091 result = runner.invoke(app, ["--name", "Camila"])92 assert "info name is: main" in result.stdout93 assert "param name is: name" in result.stdout
85 unmodified lines
179 app = typer.Typer()180181 @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}")188189 result = runner.invoke(app, ["Hello", "2", "invalid"])190 # TODO: when deprecating Click 7, remove second option191192 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 lines
added:tests/test_rich_utils.py+38 added
1import typer2import typer.completion3from typer.testing import CliRunner45runner = CliRunner()678def test_rich_utils_click_rewrapp():9 app = typer.Typer(rich_markup_mode="markdown")1011 @app.command()12 def main():13 """14 \b15 Some text1617 Some unwrapped text18 """19 print("Hello World")2021 @app.command()22 def secondary():23 """24 \b25 Secondary text2627 Some unwrapped text28 """29 print("Hello Secondary World")3031 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.stdout
modified:tests/test_tracebacks.py+29 added
1import os2import subprocess3from pathlib import Path45
3 unmodified lines
9 ["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.stderr1617 assert "typer.run(main)" not in result.stderr
6 unmodified lines
24 )25 assert "name = 'morty'" in result.stderr262728def 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.stderr3839 assert "typer.run(main)" in result.stderr40 assert "print(name + 3)" in result.stderr4142 # 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.stderr484950def 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.stderr6061 assert "app()" in result.stderr
13 unmodified lines
75 ["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.stderr8283 assert "typer.run(main)" in result.stderr
11 unmodified lines
95 ["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.stderr102103 assert "app()" in result.stderr
11 unmodified lines
115 ["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 lines
138 ["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.stderr145146 assert "app()" in result.stderr
6 unmodified lines
modified:tests/test_type_conversion.py+3 added-3 removed
13 unmodified lines
1415 @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")2122 result = runner.invoke(app)23 assert result.exit_code == 024 assert "No user" in result.output
7 unmodified lines
32 app = typer.Typer()3334 @app.command()35 def no_type(user):36 typer.echo(f"User: {user}")36 print(f"User: {user}")3738 result = runner.invoke(app, ["Camila"])39 assert result.exit_code == 040 assert "User: Camila" in result.output
52 unmodified lines
added:typer/_compat_utils.py+5 added
1import click234def _get_click_major() -> int:5 return int(click.__version__.split(".")[0])
modified:typer/completion.py+2 added-1 removed
2 unmodified lines
3from typing import Any, Dict, Tuple45import click67from ._compat_utils import _get_click_major8from ._completion_shared import Shells, get_completion_script, install9from .models import ParamMeta10from .params import Option10from .utils import _get_click_major, get_params_from_function11from .utils import get_params_from_function1213try:14 import shellingham15except ImportError: # pragma: nocover
145 unmodified lines
modified:typer/core.py+373 added-48 removed
1import errno2import inspect3import os4import sys5from gettext import gettext as _
4 unmodified lines
10 Dict,11 List,12 Optional,13 Sequence,14 TextIO,15 Tuple,16 Union,17 cast,18)
2 unmodified lines
21import click.core22import click.formatting23import click.parser24import click.types25import click.utils26from typer.completion import completion_init2724from .utils import _get_click_major28from ._compat_utils import _get_click_major2930if sys.version_info >= (3, 8):31 from typing import Literal32else:33 from typing_extensions import Literal3435try:36 import rich3738 from . import rich_utils3940except ImportError: # pragma: nocover41 rich = None # type: ignore4243if TYPE_CHECKING: # pragma: no cover44 if _get_click_major() == 7:27 import click.shell_completion45 import click.shell_completion4647MarkupMode = Literal["markdown", "rich", None]484950# TODO: when deprecating Click 7, remove this51def _typer_param_shell_complete(52 self: click.core.Parameter, ctx: click.Context, incomplete: str53) -> List["click.shell_completion.CompletionItem"]:
48 unmodified lines
102103 self._custom_shell_complete = compat_autocompletion104105106def _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_string146147148def _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 = True158159 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_value170171172def _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:]187188 # 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)193194 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_str199200 prog_name = make_str(201 os.path.basename(sys.argv[0] if sys.argv else __file__)202 )203204 # 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: ignore210211 _bashcomplete(self, prog_name, complete_var)212213 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)270271272class TyperArgument(click.core.Argument):273 def __init__(274 self,275 *,
20 unmodified lines
296 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 lines
327 _typer_param_setup_autocompletion_compat(328 self, autocompletion=autocompletion329 )330331 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 )344345 def _extract_default_help_str(346 self, *, ctx: click.Context347 ) -> Optional[Union[Any, Callable[[], Any]]]:348 return _extract_default_help_str(self, ctx=ctx)349350 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 lines
364 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}")368369 # 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 end373374 show_default_is_str = isinstance(self.show_default, str)375376 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 lines
450 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 lines
490 if _get_click_major() > 7:491 _typer_param_setup_autocompletion_compat(492 self, autocompletion=autocompletion493 )494 self.rich_help_panel = rich_help_panel495496 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 )509510 def _extract_default_help_str(511 self, *, ctx: click.Context512 ) -> Optional[Union[Any, Callable[[], Any]]]:513 return _extract_default_help_str(self, ctx=ctx)514515 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 lines
563 else ", ".join(str(d) for d in envvar)564 )565 extra.append(_("env var: {var}").format(var=var_str))566326 # 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 end571332 try:333 default_value = self.get_default(ctx, call=False)334 finally:335 ctx.resilient_parsing = resilient336572 show_default_is_str = isinstance(self.show_default, str)573574 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)367577 # 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))587588 if isinstance(self.type, click.types._NumberRangeBase):
63 unmodified lines
652 sys.exit(rv)653654655class 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_panel691692 def format_options(693 self, ctx: click.Context, formatter: click.HelpFormatter694 ) -> None:695 _typer_format_options(self, ctx=ctx, formatter=formatter)
7 unmodified lines
703 _typer_main_shell_completion(704 self, ctx_args=ctx_args, prog_name=prog_name, complete_var=complete_var705 )706707 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 )725726 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 )734735736class 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_panel752753 def format_options(754 self, ctx: click.Context, formatter: click.HelpFormatter755 ) -> None:756 _typer_format_options(self, ctx=ctx, formatter=formatter)
7 unmodified lines
764 ) -> None:765 _typer_main_shell_completion(766 self, ctx_args=ctx_args, prog_name=prog_name, complete_var=complete_var767 )768769 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 )787788 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 lines
1314import click1516from .completion import get_completion_inspect_parameters17from .core import TyperArgument, TyperCommand, TyperGroup, TyperOption17from .core import MarkupMode, TyperArgument, TyperCommand, TyperGroup, TyperOption18from .models import (19 AnyType,20 ArgumentInfo,21 CommandFunctionType,
33 unmodified lines
55) -> 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 lines
115 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 lines
132 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 lines
171 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 lines
186 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 lines
207 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 f214215 return decorator
1 unmodified line
217 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 line
227 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 lines
248 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 lines
261 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 lines
277 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 lines
299 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 )306307 def __call__(self, *args: Any, **kwargs: Any) -> Any:
23 unmodified lines
331def 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 group338339
21 unmodified lines
361 ):362 single_command.context_settings = typer_instance.info.context_settings363364 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 lines
469 return TyperInfo(**values)470471472def 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 lines
501 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 lines
518 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 group535536
20 unmodified lines
557 return params, convertors, context_param_name558559560def 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.help
25 unmodified lines
594 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 command603604
292 unmodified lines
897 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 lines
930 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 cover
111 unmodified lines
modified:typer/models.py+30 added-7 removed
13 unmodified lines
14)1516import click1718from ._compat_utils import _get_click_major1920if TYPE_CHECKING: # pragma: no cover21 if _get_click_major() > 7:19 import click.shell_completion22 import click.shell_completion2324 from .core import TyperCommand, TyperGroup21 from .main import Typer # noqa25 from .main import Typer262728NoneType = type(None)29
60 unmodified lines
90 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 lines
101 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_settings
5 unmodified lines
116 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_panel122123124class 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 lines
142 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 = cls
10 unmodified lines
162 self.options_metavar = options_metavar163 self.add_help_option = add_help_option164 self.hidden = hidden165 self.deprecated = deprecated166 self.rich_help_panel = rich_help_panel167168169class ParameterInfo:170 def __init__(
25 unmodified lines
196 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 lines
212 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 = callback
31 unmodified lines
253 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_panel259260261class OptionInfo(ParameterInfo):262 def __init__(
34 unmodified lines
297 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 lines
313 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 lines
355 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_required
35 unmodified lines
400 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 lines
416 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 lines
458 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 )465466467class ParamMeta:
25 unmodified lines
modified:typer/params.py+10 added-2 removed
43 unmodified lines
44 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 lines
60 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 lines
111 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 )118119120def Argument(
24 unmodified lines
145 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 lines
161 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 lines
206 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-click23import inspect4import sys5from collections import defaultdict6from os import getenv7from typing import Any, DefaultDict, Dict, Iterable, List, Optional, Union89import click10from rich import box11from rich.align import Align12from rich.columns import Columns13from rich.console import Console, RenderableType, group14from rich.emoji import Emoji15from rich.highlighter import RegexHighlighter16from rich.markdown import Markdown17from rich.padding import Padding18from rich.panel import Panel19from rich.table import Table20from rich.text import Text21from rich.theme import Theme2223if sys.version_info >= (3, 8):24 from typing import Literal25else:26 from typing_extensions import Literal2728# Default styles29STYLE_OPTION = "bold cyan"30STYLE_SWITCH = "bold green"31STYLE_NEGATIVE_OPTION = "bold magenta"32STYLE_NEGATIVE_SWITCH = "bold red"33STYLE_METAVAR = "bold yellow"34STYLE_METAVAR_SEPARATOR = "dim"35STYLE_USAGE = "yellow"36STYLE_USAGE_COMMAND = "bold"37STYLE_DEPRECATED = "red"38STYLE_DEPRECATED_COMMAND = "dim"39STYLE_HELPTEXT_FIRST_LINE = ""40STYLE_HELPTEXT = "dim"41STYLE_OPTION_HELP = ""42STYLE_OPTION_DEFAULT = "dim"43STYLE_OPTION_ENVVAR = "dim yellow"44STYLE_REQUIRED_SHORT = "red"45STYLE_REQUIRED_LONG = "dim red"46STYLE_OPTIONS_PANEL_BORDER = "dim"47ALIGN_OPTIONS_PANEL: Literal["left", "center", "right"] = "left"48STYLE_OPTIONS_TABLE_SHOW_LINES = False49STYLE_OPTIONS_TABLE_LEADING = 050STYLE_OPTIONS_TABLE_PAD_EDGE = False51STYLE_OPTIONS_TABLE_PADDING = (0, 1)52STYLE_OPTIONS_TABLE_BOX = ""53STYLE_OPTIONS_TABLE_ROW_STYLES = None54STYLE_OPTIONS_TABLE_BORDER_STYLE = None55STYLE_COMMANDS_PANEL_BORDER = "dim"56ALIGN_COMMANDS_PANEL: Literal["left", "center", "right"] = "left"57STYLE_COMMANDS_TABLE_SHOW_LINES = False58STYLE_COMMANDS_TABLE_LEADING = 059STYLE_COMMANDS_TABLE_PAD_EDGE = False60STYLE_COMMANDS_TABLE_PADDING = (0, 1)61STYLE_COMMANDS_TABLE_BOX = ""62STYLE_COMMANDS_TABLE_ROW_STYLES = None63STYLE_COMMANDS_TABLE_BORDER_STYLE = None64STYLE_ERRORS_PANEL_BORDER = "red"65ALIGN_ERRORS_PANEL: Literal["left", "center", "right"] = "left"66STYLE_ERRORS_SUGGESTION = "dim"67STYLE_ABORTED = "red"68_TERMINAL_WIDTH = getenv("TERMINAL_WIDTH")69MAX_WIDTH = int(_TERMINAL_WIDTH) if _TERMINAL_WIDTH else None70COLOR_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")74FORCE_TERMINAL = bool(75 not _TYPER_FORCE_DISABLE_TERMINAL76 and getenv("GITHUB_ACTIONS")77 or getenv("FORCE_COLOR")78 or getenv("PY_COLORS")79)8081# Fixed strings82DEPRECATED_STRING = "(deprecated) "83DEFAULT_STRING = "[default: {}]"84ENVVAR_STRING = "[env var: {}]"85REQUIRED_SHORT_STRING = "*"86REQUIRED_LONG_STRING = "[required]"87RANGE_STRING = " [{}]"88ARGUMENTS_PANEL_TITLE = "Arguments"89OPTIONS_PANEL_TITLE = "Options"90COMMANDS_PANEL_TITLE = "Commands"91ERRORS_PANEL_TITLE = "Error"92ABORTED_TEXT = "Aborted."9394MARKUP_MODE_MARKDOWN = "markdown"95MARKUP_MODE_RICH = "rich"96_RICH_HELP_PANEL_NAME = "rich_help_panel"9798MarkupMode = Literal["markdown", "rich", None]99100101# Rich regex highlighter102class OptionHighlighter(RegexHighlighter):103 """Highlights our special options."""104105 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 ]111112113class 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 ]118119120highlighter = OptionHighlighter()121negative_highlighter = NegativeOptionHighlighter()122123124def _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 )143144145def _make_rich_rext(146 *, text: str, style: str = "", markup_mode: MarkupMode147) -> Union[Markdown, Text]:148 """Take a string, remove indentations, and return styled text.149150 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.153154 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))166167168@group()169def _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.175176 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)183184 # Fetch and dedent the help text185 help_text = inspect.cleandoc(obj.help or "")186187 # Trim off anything that comes after \f on its own line188 help_text = help_text.partition("\f")[0]189190 # 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 )200201 # 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)217218 yield _make_rich_rext(219 text=remaining_lines,220 style=STYLE_HELPTEXT,221 markup_mode=markup_mode,222 )223224225def _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.232233 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, TyperOption240241 items: List[Union[Text, Markdown]] = []242243 # Get the environment variable first244245 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 )259260 # 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 )279280 # 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))283284 # 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 )302303 # Required?304 if param.required:305 items.append(Text(REQUIRED_LONG_STRING, style=STYLE_REQUIRED_LONG))306307 # Use Columns - this allows us to group different renderable types308 # (Text, Markdown) onto a single line.309 return Columns(items)310311312def _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.318319 That is, when calling help on groups with multiple subcommands320 (not the main help text when calling the subcommand help).321322 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 )337338339def _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)365366 # Column for a metavar, if we have one367 metavar = Text(style=STYLE_METAVAR, overflow="fold")368 metavar_str = param.make_metavar()369370 # 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()377378 # Skip booleans and choices (handled above)379 if metavar_str != "BOOLEAN":380 metavar.append(metavar_str)381382 # 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 pass397398 # Required asterisk399 required: Union[str, Text] = ""400 if param.required:401 required = Text(REQUIRED_SHORT_STRING, style=STYLE_REQUIRED_SHORT)402403 # 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 ]410411 metavar_highlighter = MetavarHighlighter()412413 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)445446 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 )463464465def _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)482483 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 )529530531def 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.538539 Based on original code from rich-cli, by @willmcgugan.540 https://github.com/Textualize/rich-cli/blob/8a2767c7a340715fc6fbf4930ace717b9b2fc5e5/src/rich_cli/__main__.py#L162-L236541542 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()546547 # Print usage548 console.print(549 Padding(highlighter(obj.get_usage(ctx)), 1), style=STYLE_USAGE_COMMAND550 )551552 # Print command / group help if we have some553 if obj.help:554555 # 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):571572 # 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 )623624 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)634635 # 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 )653654 # 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))661662663def rich_format_error(self: click.ClickException) -> None:664 """Print richly formatted click errors.665666 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())673674 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 )679680 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 )688689690def 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
1import inspect2from typing import Any, Callable, Dict, get_type_hints34import click54from .models import ParamMeta567def get_params_from_function(func: Callable[..., Any]) -> Dict[str, ParamMeta]:
7 unmodified lines
15 params[param.name] = ParamMeta(16 name=param.name, default=param.default, annotation=annotation17 )18 return params212223def _get_click_major() -> int:24 return int(click.__version__.split(".")[0])
modified:README.md+88 added-59 removed
54 unmodified lines
5556<div class="termy">5758```console59$ pip install typer59$ pip install "typer[all]"60---> 100%61Successfully installed typer62```6364</div>6566**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.6768## Example6970### The absolute minimum71
3 unmodified lines
75import typer767778def main(name: str):77 typer.echo(f"Hello {name}")79 print(f"Hello {name}")808182if __name__ == "__main__":83 typer.run(main)
9 unmodified lines
93// Run your application94$ python main.py9596// You get a nice error, you are missing NAME95Usage: main.py [OPTIONS] NAME96Try "main.py --help" for help.97<font color="#F4BF75">Usage: </font>main.py [OPTIONS] NAME98<font color="#A5A5A1">Try </font><font color="#44919F">&apos;main.py </font><font color="#44919F"><b>--help</b></font><font color="#44919F">&apos;</font><font color="#A5A5A1"> for help.</font>99<font color="#F92672">╭─ Error ───────────────────────────────────────────╮</font>100<font color="#F92672">│</font> Missing argument &apos;NAME&apos;. <font color="#F92672">│</font>101<font color="#F92672">╰───────────────────────────────────────────────────╯</font>10298Error: Missing argument 'NAME'.103104// You get a --help for free105$ python main.py --help106103Usage: 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>124105Arguments:106 NAME [required]107108Options: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.112125// When you create a package you get ✨ auto-completion ✨ for free, installed with --install-completion126127// Now pass the NAME argument128$ python main.py Camila
26 unmodified lines
155156157@app.command()158def hello(name: str):147 typer.echo(f"Hello {name}")159 print(f"Hello {name}")160161162@app.command()163def 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}!")168169170if __name__ == "__main__":171 app()
7 unmodified lines
179* Execute the `app()` itself, as if it was a function (instead of `typer.run`).180181### Run the upgraded example182183Check the new help:184185<div class="termy">186187```console174// Check the --help188$ python main.py --help189177Usage: 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>208179Options: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```211184Commands:185 goodbye186 hello212</div>213188// You have 2 subcommands (the 2 functions): goodbye and hello214Now check the help for the `hello` command:215190// Now get the --help for hello216<div class="termy">217218```console219$ python main.py hello --help220194Usage: 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```230196Arguments:197 NAME [required]231</div>232199Options:200 --help Show this message and exit.233And now check the help for the `goodbye` command:234202// And now get the --help for goodbye235<div class="termy">236237```console238$ python main.py goodbye --help239206Usage: 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>250208Arguments:209 NAME [required]251// Automatic --formal and --no-formal for the bool option 🎉252```253211Options:212 --formal / --no-formal [default: False]213 --help Show this message and exit.254</div>255215// Automatic --formal and --no-formal for the bool option 🎉256Now you can try out the new command line application:257217// And if you use it with the hello command258<div class="termy">259260```console261// Use it with the hello command262263$ python main.py hello Camila264265Hello Camila266
47 unmodified lines
314Typer uses <a href="https://click.palletsprojects.com/" class="external-link" target="_blank">Click</a> internally. That's the only dependency.315316But you can also install extras:317274* <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`.322282You can install `typer` with `colorama` and `shellingham` with `pip install typer[all]`.323You can install `typer` with `rich` and `shellingham` with `pip install typer[all]`.324284## Other tools and plug-ins285286Click 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.287288For example:289290* <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.295325## License326327This project is licensed under the terms of the MIT license.