Skip to content
Myr

✨ Refactor and document handling pretty exceptions (#422)

Before adoption: this commit came in with the history the project adopted, so no landing records it.

* ♻️ Rename pretty_errors_ to pretty_exceptions_ to avoid confusion with validation errors * ✨ Add source examples for pretty_exceptions * 📝 Add docs for pretty exceptions * 🔧 Add Exceptions docs to MkDocs * ✅ Add tests for tutorial about exceptions * ✅ Update trackeback tests, remove tests covered by tutorial * ✅ Fix test for module

authored by Sebastián Ramírez · committed by GitHub · parent d4dff65 · Browse files · 18 files+562 added−148 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

18 files+562 added−148 removed

  • tests:+207 added−120 removed
  • other:+355 added−28 removed

18 files+562 added−148 removed

added:docs/tutorial/exceptions.md+281 added
1# Exceptions and Errors23When your code has errors and you run it, it will show the error and an exception.45Typer does some tricks to help you detect those errors quickly.67## Example Broken App89Let's take this example broken app:1011```Python hl_lines="5"12{!../docs_src/exceptions/tutorial001.py!}13```1415This code is broken because you can't sum a string and a number (`name + 3`).1617## Exceptions with Rich1819If you have **Rich** installed (for example if you installed `"typer[all]"`), **Typer** will use it to automatically show you nicely printed errors.2021It will **omit** all the parts of the traceback (the chain of things that called your function) that come from the internal parts in Typer and Click.2223So, the error you see will be **much clearer** and simpler, to help you detect the problem in your code quickly:2425<div class="termy">2627```console28$ python main.py2930<font color="#F92672">╭──────────────── </font><font color="#F92672"><b>Traceback (most recent call last)</b></font><font color="#F92672"> ────────────────╮</font>31<font color="#F92672">│</font> <font color="#A37F4E">/home/user/code/superapp/</font><font color="#F4BF75"><b>main.py</b></font>:<font color="#66D9EF">5</font> in <font color="#A6E22E">main</font> <font color="#F92672">│</font>32<font color="#F92672">│</font> <font color="#F92672">│</font>33<font color="#F92672">│</font> 2 <font color="#F92672">│</font>34<font color="#F92672">│</font> 3 <font color="#F92672">│</font>35<font color="#F92672">│</font> 4 <font color="#66D9EF">def</font> <font color="#A6E22E">main</font>(name: <font color="#A1EFE4">str</font> = <font color="#F4BF75">&quot;morty&quot;</font>): <font color="#F92672">│</font>36<font color="#F92672">│</font> <font color="#F92672">❱ </font> 5 │ <font color="#A1EFE4">print</font>(name + <font color="#66D9EF">3</font>) <font color="#F92672">│</font>37<font color="#F92672">│</font> 6 <font color="#F92672">│</font>38<font color="#F92672">│</font> 7 <font color="#F92672">│</font>39<font color="#F92672">│</font> 8 <font color="#66D9EF">if</font> <font color="#F92672">__name__</font> == <font color="#F4BF75">&quot;__main__&quot;</font>: <font color="#F92672">│</font>40<font color="#F92672">│</font> <font color="#F92672">│</font>41<font color="#F92672">│</font> <font color="#F4BF75">╭──── locals ────╮</font> <font color="#F92672">│</font>42<font color="#F92672">│</font> <font color="#F4BF75">│</font> name = <font color="#F4BF75">&apos;morty&apos;</font> <font color="#F4BF75">│</font> <font color="#F92672">│</font>43<font color="#F92672">│</font> <font color="#F4BF75">╰────────────────╯</font> <font color="#F92672">│</font>44<font color="#F92672">╰───────────────────────────────────────────────────────────────────╯</font>45<font color="#F92672"><b>TypeError: </b></font>can only concatenate str <b>(</b>not <font color="#A6E22E">&quot;int&quot;</font><b>)</b> to str46```4748</div>4950## Exceptions without Rich5152If you don't have Rich installed, Typer will still do some tricks to show you the information **as clearly as possible**:5354<div class="termy">5556```console57$ python main.py5859Traceback (most recent call last):6061 File "main.py", line 12, in <module>62 typer.run(main)6364 File "main.py", line 8, in main65 print(name + 3)6667TypeError: can only concatenate str (not "int") to str68```6970</div>7172## Disable Local Variables for Security7374If your Typer application handles **delicate information**, for example a **password**, a **key**, a **token**, then it could be problematic if the automatic errors show the value in those <abbr title="a variable that lives only inside a function, its value is only visible inside of it">local variables</abbr>.7576This would be relevant in particular if your CLI application is being run on some CI (continuous integration) system that is recording the logs.7778The default errors above, when using Rich, show a section with:7980```Python81name = 'morty'82```8384In this case, `name` is a local variable, it comes from a parameter passed to the function.8586But if it was something like a password, would would have liked to hide it.8788In that case, you can create the `typer.Typer()` application explicitly and set the parameter `pretty_exceptions_show_locals=False`:8990```Python hl_lines="3"91{!../docs_src/exceptions/tutorial002.py!}92```9394And now when you run it, you will see the error without the local variables:9596<div class="termy">9798```console99$ python main.py supersecret100101<font color="#F92672">╭──────────────── </font><font color="#F92672"><b>Traceback (most recent call last)</b></font><font color="#F92672"> ────────────────╮</font>102<font color="#F92672">│</font> <font color="#A37F4E">/home/user/code/superapp/</font><font color="#F4BF75"><b>main.py</b></font>:<font color="#66D9EF">8</font> in <font color="#A6E22E">main</font> <font color="#F92672">│</font>103<font color="#F92672">│</font> <font color="#F92672">│</font>104<font color="#F92672">│</font> 5 <font color="#F92672">│</font>105<font color="#F92672">│</font> 6 <font color="#AE81FF"><b>@app</b></font>.command() <font color="#F92672">│</font>106<font color="#F92672">│</font> 7 <font color="#66D9EF">def</font> <font color="#A6E22E">main</font>(password: <font color="#A1EFE4">str</font>): <font color="#F92672">│</font>107<font color="#F92672">│</font> <font color="#F92672">❱ </font> 8 │ <font color="#A1EFE4">print</font>(password + <font color="#66D9EF">3</font>) <font color="#F92672">│</font>108<font color="#F92672">│</font> 9 <font color="#F92672">│</font>109<font color="#F92672">│</font> 10 <font color="#F92672">│</font>110<font color="#F92672">│</font> 11 <font color="#66D9EF">if</font> <font color="#F92672">__name__</font> == <font color="#F4BF75">&quot;__main__&quot;</font>: <font color="#F92672">│</font>111<font color="#F92672">╰───────────────────────────────────────────────────────────────────╯</font>112<font color="#F92672"><b>TypeError: </b></font>can only concatenate str <b>(</b>not <font color="#A6E22E">&quot;int&quot;</font><b>)</b> to str113```114115</div>116117Note that you passed the password `supersecret`, but it's not shown anywhere in the error message.118119Being able to see the values of local variables is normally very **helpful** to diagnose, **debug**, and fix problems, but if you are dealing with delicate information, now you know how to secure it. 🔒120121## Disable Short Output122123If you want to show the full exception, including the parts in Typer and Click, you can use the parameter `pretty_exceptions_short=False`:124125```Python hl_lines="3"126{!../docs_src/exceptions/tutorial003.py!}127```128129Now when you run it, you will see the whole output:130131<div class="termy">132133```console134$ python main.py135136<font color="#F92672">╭──────────────── </font><font color="#F92672"><b>Traceback (most recent call last)</b></font><font color="#F92672"> ────────────────╮</font>137<font color="#F92672">│</font> <font color="#A37F4E">/home/user/code/superapp/</font><font color="#F4BF75"><b>main.py</b></font>:<font color="#66D9EF">12</font> in <font color="#A6E22E">&lt;module&gt;</font> <font color="#F92672">│</font>138<font color="#F92672">│</font> <font color="#F92672">│</font>139<font color="#F92672">│</font> 9 <font color="#F92672">│</font>140<font color="#F92672">│</font> 10 <font color="#F92672">│</font>141<font color="#F92672">│</font> 11 <font color="#66D9EF">if</font> <font color="#F92672">__name__</font> == <font color="#F4BF75">&quot;__main__&quot;</font>: <font color="#F92672">│</font>142<font color="#F92672">│</font> <font color="#F92672">❱ </font>12 │ app() <font color="#F92672">│</font>143<font color="#F92672">│</font> 13 <font color="#F92672">│</font>144<font color="#F92672">│</font> <font color="#F92672">│</font>145<font color="#F92672">│</font> <font color="#F4BF75">╭─────────────────────────── locals ────────────────────────────╮</font> <font color="#F92672">│</font>146<font color="#F92672">│</font> <font color="#F4BF75">│</font> <font color="#A6194C">__annotations__</font> = <b>{}</b> <font color="#F4BF75">│</font> <font color="#F92672">│</font>147<font color="#F92672">│</font> <font color="#F4BF75">│</font> <font color="#A6194C">__builtins__</font> = <b>&lt;</b><font color="#AE81FF"><b>module</b></font> <font color="#F4BF75">&apos;builtins&apos;</font> <b>(</b>built-in<b>)&gt;</b> <font color="#F4BF75">│</font> <font color="#F92672">│</font>148<font color="#F92672">│</font> <font color="#F4BF75">│</font> <font color="#A6194C">__cached__</font> = <font color="#66D9EF">None</font> <font color="#F4BF75">│</font> <font color="#F92672">│</font>149<font color="#F92672">│</font> <font color="#F4BF75">│</font> <font color="#A6194C">__doc__</font> = <font color="#66D9EF">None</font> <font color="#F4BF75">│</font> <font color="#F92672">│</font>150<font color="#F92672">│</font> <font color="#F4BF75">│</font> <font color="#A6194C">__file__</font> = <font color="#F4BF75">&apos;main.py&apos;</font> <font color="#F4BF75">│</font> <font color="#F92672">│</font>151<font color="#F92672">│</font> <font color="#F4BF75">│</font> <font color="#A6194C">__loader__</font> = <b>&lt;</b><font color="#AE81FF"><b>_frozen_importlib_external.SourceFileLoad…</b></font> <font color="#F4BF75">│</font> <font color="#F92672">│</font>152<font color="#F92672">│</font> <font color="#F4BF75">│</font> object at <font color="#66D9EF">0x7f047db1c050</font><b>&gt;</b> <font color="#F4BF75">│</font> <font color="#F92672">│</font>153<font color="#F92672">│</font> <font color="#F4BF75">│</font> <font color="#A6194C">__name__</font> = <font color="#F4BF75">&apos;__main__&apos;</font> <font color="#F4BF75">│</font> <font color="#F92672">│</font>154<font color="#F92672">│</font> <font color="#F4BF75">│</font> <font color="#A6194C">__package__</font> = <font color="#66D9EF">None</font> <font color="#F4BF75">│</font> <font color="#F92672">│</font>155<font color="#F92672">│</font> <font color="#F4BF75">│</font> <font color="#A6194C">__spec__</font> = <font color="#66D9EF">None</font> <font color="#F4BF75">│</font> <font color="#F92672">│</font>156<font color="#F92672">│</font> <font color="#F4BF75">│</font> app = <b>&lt;</b><font color="#AE81FF"><b>typer.main.Typer</b></font> object at <font color="#66D9EF">0x7f047db51d90</font><b>&gt;</b> <font color="#F4BF75">│</font> <font color="#F92672">│</font>157<font color="#F92672">│</font> <font color="#F4BF75">│</font> main = <b>&lt;</b><font color="#AE81FF"><b>function</b></font> main at <font color="#66D9EF">0x7f047db56830</font><b>&gt;</b> <font color="#F4BF75">│</font> <font color="#F92672">│</font>158<font color="#F92672">│</font> <font color="#F4BF75">│</font> typer = <b>&lt;</b><font color="#AE81FF"><b>module</b></font> <font color="#F4BF75">&apos;typer&apos;</font> from <font color="#F4BF75">│</font> <font color="#F92672">│</font>159<font color="#F92672">│</font> <font color="#F4BF75">│</font> <font color="#F4BF75">&apos;/home/user/code/superapp/env/lib/python3.…</font> <font color="#F4BF75">│</font> <font color="#F92672">│</font>160<font color="#F92672">│</font> <font color="#F4BF75">╰───────────────────────────────────────────────────────────────╯</font> <font color="#F92672">│</font>161<font color="#F92672">│</font> <font color="#F92672">│</font>162<font color="#F92672">│</font> <font color="#A37F4E">/home/user/code/superapp/env/lib/python3.7/site-packages/typer/</font><font color="#F4BF75"><b>ma</b></font> <font color="#F92672">│</font>163<font color="#F92672">│</font> <font color="#F4BF75"><b>in.py</b></font>:<font color="#66D9EF">328</font> in <font color="#A6E22E">__call__</font> <font color="#F92672">│</font>164<font color="#F92672">│</font> <font color="#F92672">│</font>165<font color="#F92672">│</font> <font color="#A37F4E">/home/user/code/superapp/env/lib/python3.7/site-packages/typer/</font><font color="#F4BF75"><b>ma</b></font> <font color="#F92672">│</font>166<font color="#F92672">│</font> <font color="#F4BF75"><b>in.py</b></font>:<font color="#66D9EF">311</font> in <font color="#A6E22E">__call__</font> <font color="#F92672">│</font>167<font color="#F92672">│</font> <font color="#F92672">│</font>168<font color="#F92672">│</font> <font color="#A37F4E">/home/user/code/superapp/env/lib/python3.7/site-packages/click/</font><font color="#F4BF75"><b>co</b></font> <font color="#F92672">│</font>169<font color="#F92672">│</font> <font color="#F4BF75"><b>re.py</b></font>:<font color="#66D9EF">1130</font> in <font color="#A6E22E">__call__</font> <font color="#F92672">│</font>170<font color="#F92672">│</font> <font color="#F92672">│</font>171<font color="#F92672">│</font> <font color="#A37F4E">/home/user/code/superapp/env/lib/python3.7/site-packages/typer/</font><font color="#F4BF75"><b>co</b></font> <font color="#F92672">│</font>172<font color="#F92672">│</font> <font color="#F4BF75"><b>re.py</b></font>:<font color="#66D9EF">723</font> in <font color="#A6E22E">main</font> <font color="#F92672">│</font>173<font color="#F92672">│</font> <font color="#F92672">│</font>174<font color="#F92672">│</font> <font color="#A37F4E">/home/user/code/superapp/env/lib/python3.7/site-packages/typer/</font><font color="#F4BF75"><b>co</b></font> <font color="#F92672">│</font>175<font color="#F92672">│</font> <font color="#F4BF75"><b>re.py</b></font>:<font color="#66D9EF">216</font> in <font color="#A6E22E">_main</font> <font color="#F92672">│</font>176<font color="#F92672">│</font> <font color="#F92672">│</font>177<font color="#F92672">│</font> <font color="#A37F4E">/home/user/code/superapp/env/lib/python3.7/site-packages/click/</font><font color="#F4BF75"><b>co</b></font> <font color="#F92672">│</font>178<font color="#F92672">│</font> <font color="#F4BF75"><b>re.py</b></font>:<font color="#66D9EF">1404</font> in <font color="#A6E22E">invoke</font> <font color="#F92672">│</font>179<font color="#F92672">│</font> <font color="#F92672">│</font>180<font color="#F92672">│</font> <font color="#A37F4E">/home/user/code/superapp/env/lib/python3.7/site-packages/click/</font><font color="#F4BF75"><b>co</b></font> <font color="#F92672">│</font>181<font color="#F92672">│</font> <font color="#F4BF75"><b>re.py</b></font>:<font color="#66D9EF">760</font> in <font color="#A6E22E">invoke</font> <font color="#F92672">│</font>182<font color="#F92672">│</font> <font color="#F92672">│</font>183<font color="#F92672">│</font> <font color="#A37F4E">/home/user/code/superapp/env/lib/python3.7/site-packages/typer/</font><font color="#F4BF75"><b>ma</b></font> <font color="#F92672">│</font>184<font color="#F92672">│</font> <font color="#F4BF75"><b>in.py</b></font>:<font color="#66D9EF">683</font> in <font color="#A6E22E">wrapper</font> <font color="#F92672">│</font>185<font color="#F92672">│</font> <font color="#F92672">│</font>186<font color="#F92672">│</font> <font color="#A37F4E">/home/user/code/superapp/</font><font color="#F4BF75"><b>main.py</b></font>:<font color="#66D9EF">8</font> in <font color="#A6E22E">main</font> <font color="#F92672">│</font>187<font color="#F92672">│</font> <font color="#F92672">│</font>188<font color="#F92672">│</font> 5 <font color="#F92672">│</font>189<font color="#F92672">│</font> 6 <font color="#AE81FF"><b>@app</b></font>.command() <font color="#F92672">│</font>190<font color="#F92672">│</font> 7 <font color="#66D9EF">def</font> <font color="#A6E22E">main</font>(name: <font color="#A1EFE4">str</font> = <font color="#F4BF75">&quot;morty&quot;</font>): <font color="#F92672">│</font>191<font color="#F92672">│</font> <font color="#F92672">❱ </font> 8 │ <font color="#A1EFE4">print</font>(name + <font color="#66D9EF">3</font>) <font color="#F92672">│</font>192<font color="#F92672">│</font> 9 <font color="#F92672">│</font>193<font color="#F92672">│</font> 10 <font color="#F92672">│</font>194<font color="#F92672">│</font> 11 <font color="#66D9EF">if</font> <font color="#F92672">__name__</font> == <font color="#F4BF75">&quot;__main__&quot;</font>: <font color="#F92672">│</font>195<font color="#F92672">│</font> <font color="#F92672">│</font>196<font color="#F92672">│</font> <font color="#F4BF75">╭──── locals ────╮</font> <font color="#F92672">│</font>197<font color="#F92672">│</font> <font color="#F4BF75">│</font> name = <font color="#F4BF75">&apos;morty&apos;</font> <font color="#F4BF75">│</font> <font color="#F92672">│</font>198<font color="#F92672">│</font> <font color="#F4BF75">╰────────────────╯</font> <font color="#F92672">│</font>199<font color="#F92672">╰───────────────────────────────────────────────────────────────────╯</font>200<font color="#F92672"><b>TypeError: </b></font>can only concatenate str <b>(</b>not <font color="#A6E22E">&quot;int&quot;</font><b>)</b> to str201```202203</div>204205## Disable Pretty Exceptions206207You can also entirely disable pretty exceptions with the parameter `pretty_exceptions_enable=False`:208209```Python hl_lines="3"210{!../docs_src/exceptions/tutorial004.py!}211```212213And now you will see the full standard exception as with any other Python program:214215<div class="termy">216217```console218$ python main.py219220Traceback (most recent call last):221 File "main.py", line 12, in <module>222 app()223 File "/home/user/code/superapp/env/lib/python3.7/site-packages/typer/main.py", line 328, in __call__224 raise e225 File "/home/user/code/superapp/env/lib/python3.7/site-packages/typer/main.py", line 311, in __call__226 return get_command(self)(*args, **kwargs)227 File "/home/user/code/superapp/env/lib/python3.7/site-packages/click/core.py", line 1130, in __call__228 return self.main(*args, **kwargs)229 File "/home/user/code/superapp/env/lib/python3.7/site-packages/typer/core.py", line 723, in main230 **extra,231 File "/home/user/code/superapp/env/lib/python3.7/site-packages/typer/core.py", line 216, in _main232 rv = self.invoke(ctx)233 File "/home/user/code/superapp/env/lib/python3.7/site-packages/click/core.py", line 1404, in invoke234 return ctx.invoke(self.callback, **ctx.params)235 File "/home/user/code/superapp/env/lib/python3.7/site-packages/click/core.py", line 760, in invoke236 return __callback(*args, **kwargs)237 File "/home/user/code/superapp/env/lib/python3.7/site-packages/typer/main.py", line 683, in wrapper238 return callback(**use_params) # type: ignore239 File "main.py", line 8, in main240 print(name + 3)241TypeError: can only concatenate str (not "int") to str242```243244</div>245246You could also achieve the same with the environment variable `_TYPER_STANDARD_TRACEBACK=1`.247248This will work for any other Typer program too, in case you need to debug a problem in a Typer program made by someone else:249250<div class="termy">251252```console253export _TYPER_STANDARD_TRACEBACK=1254$ python main.py255256257Traceback (most recent call last):258 File "main.py", line 12, in <module>259 app()260 File "/home/user/code/superapp/env/lib/python3.7/site-packages/typer/main.py", line 328, in __call__261 raise e262 File "/home/user/code/superapp/env/lib/python3.7/site-packages/typer/main.py", line 311, in __call__263 return get_command(self)(*args, **kwargs)264 File "/home/user/code/superapp/env/lib/python3.7/site-packages/click/core.py", line 1130, in __call__265 return self.main(*args, **kwargs)266 File "/home/user/code/superapp/env/lib/python3.7/site-packages/typer/core.py", line 723, in main267 **extra,268 File "/home/user/code/superapp/env/lib/python3.7/site-packages/typer/core.py", line 216, in _main269 rv = self.invoke(ctx)270 File "/home/user/code/superapp/env/lib/python3.7/site-packages/click/core.py", line 1404, in invoke271 return ctx.invoke(self.callback, **ctx.params)272 File "/home/user/code/superapp/env/lib/python3.7/site-packages/click/core.py", line 760, in invoke273 return __callback(*args, **kwargs)274 File "/home/user/code/superapp/env/lib/python3.7/site-packages/typer/main.py", line 683, in wrapper275 return callback(**use_params) # type: ignore276 File "main.py", line 8, in main277 print(name + 3)278TypeError: can only concatenate str (not "int") to str279```280281</div>
added:docs_src/exceptions/tutorial001.py+9 added
1import typer234def main(name: str = "morty"):5 print(name + 3)678if __name__ == "__main__":9 typer.run(main)
added:docs_src/exceptions/tutorial002.py+12 added
1import typer23app = typer.Typer(pretty_exceptions_show_locals=False)456@app.command()7def main(password: str):8 print(password + 3)91011if __name__ == "__main__":12 app()
added:docs_src/exceptions/tutorial003.py+12 added
1import typer23app = typer.Typer(pretty_exceptions_short=False)456@app.command()7def main(name: str = "morty"):8 print(name + 3)91011if __name__ == "__main__":12 app()
added:docs_src/exceptions/tutorial004.py+12 added
1import typer23app = typer.Typer(pretty_exceptions_enable=False)456@app.command()7def main(name: str = "morty"):8 print(name + 3)91011if __name__ == "__main__":12 app()
modified:tests/assets/type_error_no_rich_short_disable.py+1 added-1 removed
2 unmodified lines
34typer.main.rich = None567app = typer.Typer(pretty_errors_short=False)7app = typer.Typer(pretty_exceptions_short=False)8910@app.command()11def main(name: str = "morty"):
5 unmodified lines
deleted:tests/assets/type_error_rich_pretty_disable.py-12 removed
1import typer23app = typer.Typer(pretty_errors_enable=False)456@app.command()7def main(name: str = "morty"):8 print(name + 3)91011if __name__ == "__main__":12 app()
deleted:tests/assets/type_error_rich_short_disable.py-12 removed
1import typer23app = typer.Typer(pretty_errors_short=False)456@app.command()7def main(name: str = "morty"):8 print(name + 3)91011if __name__ == "__main__":12 app()
deleted:tests/assets/type_error_rich.py-9 removed
1import typer234def main(name: str = "morty"):5 print(name + 3)678if __name__ == "__main__":9 typer.run(main)
added:tests/test_tutorial/test_exceptions/__init__.py
added:tests/test_tutorial/test_exceptions/test_tutorial001.py+63 added
1import os2import subprocess3from pathlib import Path45from typer.testing import CliRunner67from docs_src.exceptions import tutorial001 as mod89runner = CliRunner()101112def test_traceback_rich():13 file_path = Path(mod.__file__)14 result = subprocess.run(15 ["coverage", "run", str(file_path)],16 stdout=subprocess.PIPE,17 stderr=subprocess.PIPE,18 encoding="utf-8",19 env={**os.environ, "_TYPER_STANDARD_TRACEBACK": ""},20 )21 assert "return get_command(self)(*args, **kwargs)" not in result.stderr2223 assert "typer.run(main)" not in result.stderr24 assert "print(name + 3)" in result.stderr2526 # TODO: when deprecating Python 3.6, remove second option27 assert (28 'TypeError: can only concatenate str (not "int") to str' in result.stderr29 or "TypeError: must be str, not int" in result.stderr30 )31 assert "name = 'morty'" in result.stderr323334def test_standard_traceback_env_var():35 file_path = Path(mod.__file__)36 result = subprocess.run(37 ["coverage", "run", str(file_path)],38 stdout=subprocess.PIPE,39 stderr=subprocess.PIPE,40 encoding="utf-8",41 env={**os.environ, "_TYPER_STANDARD_TRACEBACK": "1"},42 )43 assert "return get_command(self)(*args, **kwargs)" in result.stderr4445 assert "typer.run(main)" in result.stderr46 assert "print(name + 3)" in result.stderr4748 # TODO: when deprecating Python 3.6, remove second option49 assert (50 'TypeError: can only concatenate str (not "int") to str' in result.stderr51 or "TypeError: must be str, not int" in result.stderr52 )53 assert "name = 'morty'" not in result.stderr545556def test_script():57 result = subprocess.run(58 ["coverage", "run", mod.__file__, "--help"],59 stdout=subprocess.PIPE,60 stderr=subprocess.PIPE,61 encoding="utf-8",62 )63 assert "Usage" in result.stdout
added:tests/test_tutorial/test_exceptions/test_tutorial002.py+63 added
1import os2import subprocess3from pathlib import Path45from typer.testing import CliRunner67from docs_src.exceptions import tutorial002 as mod89runner = CliRunner()101112def test_traceback_rich():13 file_path = Path(mod.__file__)14 result = subprocess.run(15 ["coverage", "run", str(file_path), "secret"],16 stdout=subprocess.PIPE,17 stderr=subprocess.PIPE,18 encoding="utf-8",19 env={**os.environ, "_TYPER_STANDARD_TRACEBACK": ""},20 )21 assert "return get_command(self)(*args, **kwargs)" not in result.stderr2223 assert "app()" not in result.stderr24 assert "print(password + 3)" in result.stderr2526 # TODO: when deprecating Python 3.6, remove second option27 assert (28 'TypeError: can only concatenate str (not "int") to str' in result.stderr29 or "TypeError: must be str, not int" in result.stderr30 )31 assert "name = 'morty'" not in result.stderr323334def test_standard_traceback_env_var():35 file_path = Path(mod.__file__)36 result = subprocess.run(37 ["coverage", "run", str(file_path), "secret"],38 stdout=subprocess.PIPE,39 stderr=subprocess.PIPE,40 encoding="utf-8",41 env={**os.environ, "_TYPER_STANDARD_TRACEBACK": "1"},42 )43 assert "return get_command(self)(*args, **kwargs)" in result.stderr4445 assert "app()" in result.stderr46 assert "print(password + 3)" in result.stderr4748 # TODO: when deprecating Python 3.6, remove second option49 assert (50 'TypeError: can only concatenate str (not "int") to str' in result.stderr51 or "TypeError: must be str, not int" in result.stderr52 )53 assert "name = 'morty'" not in result.stderr545556def test_script():57 result = subprocess.run(58 ["coverage", "run", mod.__file__, "--help"],59 stdout=subprocess.PIPE,60 stderr=subprocess.PIPE,61 encoding="utf-8",62 )63 assert "Usage" in result.stdout
added:tests/test_tutorial/test_exceptions/test_tutorial003.py+41 added
1import os2import subprocess3from pathlib import Path45from typer.testing import CliRunner67from docs_src.exceptions import tutorial003 as mod89runner = CliRunner()101112def test_traceback_rich_pretty_short_disable():13 file_path = Path(mod.__file__)14 result = subprocess.run(15 ["coverage", "run", str(file_path)],16 stdout=subprocess.PIPE,17 stderr=subprocess.PIPE,18 encoding="utf-8",19 env={**os.environ, "_TYPER_STANDARD_TRACEBACK": ""},20 )21 assert "return get_command(self)(*args, **kwargs)" not in result.stderr2223 assert "app()" in result.stderr24 assert "print(name + 3)" in result.stderr2526 # TODO: when deprecating Python 3.6, remove second option27 assert (28 'TypeError: can only concatenate str (not "int") to str' in result.stderr29 or "TypeError: must be str, not int" in result.stderr30 )31 assert "name = 'morty'" in result.stderr323334def test_script():35 result = subprocess.run(36 ["coverage", "run", mod.__file__, "--help"],37 stdout=subprocess.PIPE,38 stderr=subprocess.PIPE,39 encoding="utf-8",40 )41 assert "Usage" in result.stdout
added:tests/test_tutorial/test_exceptions/test_tutorial004.py+39 added
1import os2import subprocess3from pathlib import Path45from typer.testing import CliRunner67from docs_src.exceptions import tutorial004 as mod89runner = CliRunner()101112def test_rich_pretty_exceptions_disable():13 file_path = Path(mod.__file__)14 result = subprocess.run(15 ["coverage", "run", str(file_path)],16 stdout=subprocess.PIPE,17 stderr=subprocess.PIPE,18 encoding="utf-8",19 env={**os.environ, "_TYPER_STANDARD_TRACEBACK": ""},20 )21 assert "return get_command(self)(*args, **kwargs)" in result.stderr2223 assert "app()" in result.stderr24 assert "print(name + 3)" in result.stderr25 # TODO: when deprecating Python 3.6, remove second option26 assert (27 'TypeError: can only concatenate str (not "int") to str' in result.stderr28 or "TypeError: must be str, not int" in result.stderr29 )303132def test_script():33 result = subprocess.run(34 ["coverage", "run", mod.__file__, "--help"],35 stdout=subprocess.PIPE,36 stderr=subprocess.PIPE,37 encoding="utf-8",38 )39 assert "Usage" in result.stdout
modified:tests/test_tracebacks.py-86 removed
1 unmodified line
2import subprocess3from pathlib import Path456def test_traceback_rich():7 file_path = Path(__file__).parent / "assets/type_error_rich.py"8 result = subprocess.run(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.stderr18 assert "print(name + 3)" in result.stderr1920 # TODO: when deprecating Python 3.6, remove second option21 assert (22 'TypeError: can only concatenate str (not "int") to str' in result.stderr23 or "TypeError: must be str, not int" in result.stderr24 )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.stderr62 assert "print(name + 3)" in result.stderr6364 # TODO: when deprecating Python 3.6, remove second option65 assert (66 'TypeError: can only concatenate str (not "int") to str' in result.stderr67 or "TypeError: must be str, not int" in result.stderr68 )69 assert "name = 'morty'" in result.stderr70716def test_traceback_no_rich():7 file_path = Path(__file__).parent / "assets/type_error_no_rich.py"8 result = subprocess.run(9 ["coverage", "run", str(file_path)],
53 unmodified lines
63 assert (64 'TypeError: can only concatenate str (not "int") to str' in result.stderr65 or "TypeError: must be str, not int" in result.stderr66 )133134135def test_rich_pretty_errors_disable():136 file_path = Path(__file__).parent / "assets/type_error_rich_pretty_disable.py"137 result = subprocess.run(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.stderr147 assert "print(name + 3)" in result.stderr148 # TODO: when deprecating Python 3.6, remove second option149 assert (150 'TypeError: can only concatenate str (not "int") to str' in result.stderr151 or "TypeError: must be str, not int" in result.stderr152 )
modified:typer/main.py+22 added-22 removed
58 unmodified lines
59 standard_traceback = os.getenv("_TYPER_STANDARD_TRACEBACK")60 if (61 standard_traceback62 or not exception_config63 or not exception_config.pretty_errors_enable63 or not exception_config.pretty_exceptions_enable64 ):65 _original_except_hook(exc_type, exc_value, tb)66 return67 typer_path = os.path.dirname(__file__)
4 unmodified lines
72 rich_tb = Traceback.from_exception(73 type(exc),74 exc,75 exc.__traceback__,76 show_locals=exception_config.pretty_errors_show_locals,76 show_locals=exception_config.pretty_exceptions_show_locals,77 suppress=supress_internal_dir_names,78 )79 console_stderr.print(rich_tb)80 return
2 unmodified lines
83 for frame in tb_exc.stack:84 if any(85 [frame.filename.startswith(path) for path in supress_internal_dir_names]86 ):87 if not exception_config.pretty_errors_short:87 if not exception_config.pretty_exceptions_short:88 # Hide the line for internal libraries, Typer and Click89 stack.append(90 traceback.FrameSummary(91 filename=frame.filename,
43 unmodified lines
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,139 pretty_exceptions_enable: bool = True,140 pretty_exceptions_show_locals: bool = True,141 pretty_exceptions_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_short146 self.pretty_exceptions_enable = pretty_exceptions_enable147 self.pretty_exceptions_show_locals = pretty_exceptions_show_locals148 self.pretty_exceptions_short = pretty_exceptions_short149 self.info = TyperInfo(150 name=name,151 cls=cls,152 invoke_without_command=invoke_without_command,
166 unmodified lines
319 setattr(320 e,321 _typer_developer_exception_attr_name,322 DeveloperExceptionConfig(323 pretty_errors_enable=self.pretty_errors_enable,324 pretty_errors_show_locals=self.pretty_errors_show_locals,325 pretty_errors_short=self.pretty_errors_short,323 pretty_exceptions_enable=self.pretty_exceptions_enable,324 pretty_exceptions_show_locals=self.pretty_exceptions_show_locals,325 pretty_exceptions_short=self.pretty_exceptions_short,326 ),327 )328 raise e329330331def 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,334 pretty_exceptions_short=typer_instance.pretty_exceptions_short,335 rich_markup_mode=typer_instance.rich_markup_mode,336 )337 return group338
23 unmodified lines
362 single_command.context_settings = typer_instance.info.context_settings363364 click_command = get_command_from_info(365 single_command,366 pretty_errors_short=typer_instance.pretty_errors_short,366 pretty_exceptions_short=typer_instance.pretty_exceptions_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)
100 unmodified lines
471472def get_group_from_info(473 group_info: TyperInfo,474 *,475 pretty_errors_short: bool,475 pretty_exceptions_short: bool,476 rich_markup_mode: MarkupMode,477) -> click.Command:478 assert (479 group_info.typer_instance
1 unmodified line
481 commands: Dict[str, click.Command] = {}482 for command_info in group_info.typer_instance.registered_commands:483 command = get_command_from_info(484 command_info=command_info,485 pretty_errors_short=pretty_errors_short,485 pretty_exceptions_short=pretty_exceptions_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(492 sub_group_info,493 pretty_errors_short=pretty_errors_short,493 pretty_exceptions_short=pretty_exceptions_short,494 rich_markup_mode=rich_markup_mode,495 )496 if sub_group.name:497 commands[sub_group.name] = sub_group
18 unmodified lines
516 callback=solved_info.callback,517 params=params,518 convertors=convertors,519 context_param_name=context_param_name,520 pretty_errors_short=pretty_errors_short,520 pretty_exceptions_short=pretty_exceptions_short,521 ),522 params=params,523 help=solved_info.help,524 epilog=solved_info.epilog,
34 unmodified lines
559560def get_command_from_info(561 command_info: CommandInfo,562 *,563 pretty_errors_short: bool,563 pretty_exceptions_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__)
15 unmodified lines
583 callback=command_info.callback,584 params=params,585 convertors=convertors,586 context_param_name=context_param_name,587 pretty_errors_short=pretty_errors_short,587 pretty_exceptions_short=pretty_exceptions_short,588 ),589 params=params, # type: ignore590 help=use_help,591 epilog=command_info.epilog,
66 unmodified lines
658 callback: Optional[Callable[..., Any]] = None,659 params: Sequence[click.Parameter] = [],660 convertors: Dict[str, Callable[[str], Any]] = {},661 context_param_name: Optional[str] = None,662 pretty_errors_short: bool,662 pretty_exceptions_short: bool,663) -> Optional[Callable[..., Any]]:664 if not callback:665 return None666 parameters = get_params_from_function(callback)
4 unmodified lines
671 if param.name:672 use_params[param.name] = param.default673674 def wrapper(**kwargs: Any) -> Any:675 _rich_traceback_guard = pretty_errors_short # noqa: F841675 _rich_traceback_guard = pretty_exceptions_short # noqa: F841676 for k, v in kwargs.items():677 if k in convertors:678 use_params[k] = convertors[k](v)679 else:
371 unmodified lines
modified:typer/models.py+6 added-6 removed
481 unmodified lines
482class DeveloperExceptionConfig:483 def __init__(484 self,485 *,486 pretty_errors_enable: bool = True,487 pretty_errors_show_locals: bool = True,488 pretty_errors_short: bool = True,486 pretty_exceptions_enable: bool = True,487 pretty_exceptions_show_locals: bool = True,488 pretty_exceptions_short: bool = True,489 ) -> None:490 self.pretty_errors_enable = pretty_errors_enable491 self.pretty_errors_show_locals = pretty_errors_show_locals492 self.pretty_errors_short = pretty_errors_short490 self.pretty_exceptions_enable = pretty_exceptions_enable491 self.pretty_exceptions_show_locals = pretty_exceptions_show_locals492 self.pretty_exceptions_short = pretty_exceptions_short
modified:mkdocs.yml+1 added
77 unmodified lines
78 - Launching Applications: tutorial/launch.md79 - Testing: tutorial/testing.md80 - Using Click: tutorial/using-click.md81 - Building a Package: tutorial/package.md82 - tutorial/exceptions.md83 - Typer CLI - completion for small scripts: typer-cli.md84 - Alternatives, Inspiration and Comparisons: alternatives.md85 - Help Typer - Get Help: help-typer.md86 - Development - Contributing: contributing.md
46 unmodified lines