✨ 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
Provenance
- Commit
c750f82- Tree
5d4a6b8- Author
Sebastián Ramírez <tiangolo@gmail.com>- Committer
GitHub <noreply@github.com>- Parent
d4dff65
18 files changed+562 added−148 removed
added:docs/tutorial/exceptions.md+281 added
1+# Exceptions and Errors2+3+When your code has errors and you run it, it will show the error and an exception.4+5+Typer does some tricks to help you detect those errors quickly.6+7+## Example Broken App8+9+Let's take this example broken app:10+11+```Python hl_lines="5"12+{!../docs_src/exceptions/tutorial001.py!}13+```14+15+This code is broken because you can't sum a string and a number (`name + 3`).16+17+## Exceptions with Rich18+19+If you have **Rich** installed (for example if you installed `"typer[all]"`), **Typer** will use it to automatically show you nicely printed errors.20+21+It 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.22+23+So, the error you see will be **much clearer** and simpler, to help you detect the problem in your code quickly:24+25+<div class="termy">26+27+```console28+$ python main.py29+30+<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">"morty"</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">"__main__"</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">'morty'</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">"int"</font><b>)</b> to str46+```47+48+</div>49+50+## Exceptions without Rich51+52+If you don't have Rich installed, Typer will still do some tricks to show you the information **as clearly as possible**:53+54+<div class="termy">55+56+```console57+$ python main.py58+59+Traceback (most recent call last):60+61+ File "main.py", line 12, in <module>62+ typer.run(main)63+64+ File "main.py", line 8, in main65+ print(name + 3)66+67+TypeError: can only concatenate str (not "int") to str68+```69+70+</div>71+72+## Disable Local Variables for Security73+74+If 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>.75+76+This would be relevant in particular if your CLI application is being run on some CI (continuous integration) system that is recording the logs.77+78+The default errors above, when using Rich, show a section with:79+80+```Python81+name = 'morty'82+```83+84+In this case, `name` is a local variable, it comes from a parameter passed to the function.85+86+But if it was something like a password, would would have liked to hide it.87+88+In that case, you can create the `typer.Typer()` application explicitly and set the parameter `pretty_exceptions_show_locals=False`:89+90+```Python hl_lines="3"91+{!../docs_src/exceptions/tutorial002.py!}92+```93+94+And now when you run it, you will see the error without the local variables:95+96+<div class="termy">97+98+```console99+$ python main.py supersecret100+101+<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">"__main__"</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">"int"</font><b>)</b> to str113+```114+115+</div>116+117+Note that you passed the password `supersecret`, but it's not shown anywhere in the error message.118+119+Being 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. 🔒120+121+## Disable Short Output122+123+If you want to show the full exception, including the parts in Typer and Click, you can use the parameter `pretty_exceptions_short=False`:124+125+```Python hl_lines="3"126+{!../docs_src/exceptions/tutorial003.py!}127+```128+129+Now when you run it, you will see the whole output:130+131+<div class="termy">132+133+```console134+$ python main.py135+136+<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"><module></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">"__main__"</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><</b><font color="#AE81FF"><b>module</b></font> <font color="#F4BF75">'builtins'</font> <b>(</b>built-in<b>)></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">'main.py'</font> <font color="#F4BF75">│</font> <font color="#F92672">│</font>151+<font color="#F92672">│</font> <font color="#F4BF75">│</font> <font color="#A6194C">__loader__</font> = <b><</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>></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">'__main__'</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><</b><font color="#AE81FF"><b>typer.main.Typer</b></font> object at <font color="#66D9EF">0x7f047db51d90</font><b>></b> <font color="#F4BF75">│</font> <font color="#F92672">│</font>157+<font color="#F92672">│</font> <font color="#F4BF75">│</font> main = <b><</b><font color="#AE81FF"><b>function</b></font> main at <font color="#66D9EF">0x7f047db56830</font><b>></b> <font color="#F4BF75">│</font> <font color="#F92672">│</font>158+<font color="#F92672">│</font> <font color="#F4BF75">│</font> typer = <b><</b><font color="#AE81FF"><b>module</b></font> <font color="#F4BF75">'typer'</font> from <font color="#F4BF75">│</font> <font color="#F92672">│</font>159+<font color="#F92672">│</font> <font color="#F4BF75">│</font> <font color="#F4BF75">'/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">"morty"</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">"__main__"</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">'morty'</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">"int"</font><b>)</b> to str201+```202+203+</div>204+205+## Disable Pretty Exceptions206+207+You can also entirely disable pretty exceptions with the parameter `pretty_exceptions_enable=False`:208+209+```Python hl_lines="3"210+{!../docs_src/exceptions/tutorial004.py!}211+```212+213+And now you will see the full standard exception as with any other Python program:214+215+<div class="termy">216+217+```console218+$ python main.py219+220+Traceback (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)241+TypeError: can only concatenate str (not "int") to str242+```243+244+</div>245+246+You could also achieve the same with the environment variable `_TYPER_STANDARD_TRACEBACK=1`.247+248+This will work for any other Typer program too, in case you need to debug a problem in a Typer program made by someone else:249+250+<div class="termy">251+252+```console253+export _TYPER_STANDARD_TRACEBACK=1254+$ python main.py255+256+257+Traceback (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)278+TypeError: can only concatenate str (not "int") to str279+```280+281+</div>added:docs_src/exceptions/tutorial001.py+9 added
1+import typer2+3+4+def main(name: str = "morty"):5+ print(name + 3)6+7+8+if __name__ == "__main__":9+ typer.run(main)added:docs_src/exceptions/tutorial002.py+12 added
1+import typer2+3+app = typer.Typer(pretty_exceptions_show_locals=False)4+5+6+@app.command()7+def main(password: str):8+ print(password + 3)9+10+11+if __name__ == "__main__":12+ app()added:docs_src/exceptions/tutorial003.py+12 added
1+import typer2+3+app = typer.Typer(pretty_exceptions_short=False)4+5+6+@app.command()7+def main(name: str = "morty"):8+ print(name + 3)9+10+11+if __name__ == "__main__":12+ app()added:docs_src/exceptions/tutorial004.py+12 added
1+import typer2+3+app = typer.Typer(pretty_exceptions_enable=False)4+5+6+@app.command()7+def main(name: str = "morty"):8+ print(name + 3)9+10+11+if __name__ == "__main__":12+ app()modified:tests/assets/type_error_no_rich_short_disable.py+1 added-1 removed
2 unmodified lines3 4 typer.main.rich = None5 6 7-app = typer.Typer(pretty_errors_short=False)7+app = typer.Typer(pretty_exceptions_short=False)8 9 10 @app.command()11 def main(name: str = "morty"):5 unmodified linesdeleted:tests/assets/type_error_rich_pretty_disable.py-12 removed
1-import typer2-3-app = typer.Typer(pretty_errors_enable=False)4-5-6-@app.command()7-def main(name: str = "morty"):8- print(name + 3)9-10-11-if __name__ == "__main__":12- app()deleted:tests/assets/type_error_rich_short_disable.py-12 removed
1-import typer2-3-app = typer.Typer(pretty_errors_short=False)4-5-6-@app.command()7-def main(name: str = "morty"):8- print(name + 3)9-10-11-if __name__ == "__main__":12- app()deleted:tests/assets/type_error_rich.py-9 removed
1-import typer2-3-4-def main(name: str = "morty"):5- print(name + 3)6-7-8-if __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
1+import os2+import subprocess3+from pathlib import Path4+5+from typer.testing import CliRunner6+7+from docs_src.exceptions import tutorial001 as mod8+9+runner = CliRunner()10+11+12+def 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.stderr22+23+ assert "typer.run(main)" not in result.stderr24+ assert "print(name + 3)" in result.stderr25+26+ # 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.stderr32+33+34+def 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.stderr44+45+ assert "typer.run(main)" in result.stderr46+ assert "print(name + 3)" in result.stderr47+48+ # 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.stderr54+55+56+def 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.stdoutadded:tests/test_tutorial/test_exceptions/test_tutorial002.py+63 added
1+import os2+import subprocess3+from pathlib import Path4+5+from typer.testing import CliRunner6+7+from docs_src.exceptions import tutorial002 as mod8+9+runner = CliRunner()10+11+12+def 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.stderr22+23+ assert "app()" not in result.stderr24+ assert "print(password + 3)" in result.stderr25+26+ # 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.stderr32+33+34+def 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.stderr44+45+ assert "app()" in result.stderr46+ assert "print(password + 3)" in result.stderr47+48+ # 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.stderr54+55+56+def 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.stdoutadded:tests/test_tutorial/test_exceptions/test_tutorial003.py+41 added
1+import os2+import subprocess3+from pathlib import Path4+5+from typer.testing import CliRunner6+7+from docs_src.exceptions import tutorial003 as mod8+9+runner = CliRunner()10+11+12+def 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.stderr22+23+ assert "app()" in result.stderr24+ assert "print(name + 3)" in result.stderr25+26+ # 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.stderr32+33+34+def 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.stdoutadded:tests/test_tutorial/test_exceptions/test_tutorial004.py+39 added
1+import os2+import subprocess3+from pathlib import Path4+5+from typer.testing import CliRunner6+7+from docs_src.exceptions import tutorial004 as mod8+9+runner = CliRunner()10+11+12+def 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.stderr22+23+ 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+ )30+31+32+def 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.stdoutmodified:tests/test_tracebacks.py-86 removed
1 unmodified line2 import subprocess3 from pathlib import Path4 5 6-def 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.stderr16-17- assert "typer.run(main)" not in result.stderr18- assert "print(name + 3)" in result.stderr19-20- # 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.stderr26-27-28-def test_standard_traceback_env_var():29- file_path = Path(__file__).parent / "assets/type_error_rich.py"30- result = subprocess.run(31- ["coverage", "run", str(file_path)],32- stdout=subprocess.PIPE,33- stderr=subprocess.PIPE,34- encoding="utf-8",35- env={**os.environ, "_TYPER_STANDARD_TRACEBACK": "1"},36- )37- assert "return get_command(self)(*args, **kwargs)" in result.stderr38-39- assert "typer.run(main)" in result.stderr40- assert "print(name + 3)" in result.stderr41-42- # TODO: when deprecating Python 3.6, remove second option43- assert (44- 'TypeError: can only concatenate str (not "int") to str' in result.stderr45- or "TypeError: must be str, not int" in result.stderr46- )47- assert "name = 'morty'" not in result.stderr48-49-50-def test_traceback_rich_pretty_short_disable():51- file_path = Path(__file__).parent / "assets/type_error_rich_short_disable.py"52- result = subprocess.run(53- ["coverage", "run", str(file_path)],54- stdout=subprocess.PIPE,55- stderr=subprocess.PIPE,56- encoding="utf-8",57- env={**os.environ, "_TYPER_STANDARD_TRACEBACK": ""},58- )59- assert "return get_command(self)(*args, **kwargs)" not in result.stderr60-61- assert "app()" in result.stderr62- assert "print(name + 3)" in result.stderr63-64- # 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.stderr70-71-6 def 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 lines63 assert (64 'TypeError: can only concatenate str (not "int") to str' in result.stderr65 or "TypeError: must be str, not int" in result.stderr66 )133-134-135-def 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.stderr145-146- 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 lines59 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 lines72 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 return2 unmodified lines83 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 lines135 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 lines319 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 e329 330 331 def get_group(typer_instance: Typer) -> click.Command:332 group = get_group_from_info(333 TyperInfo(typer_instance),334- pretty_errors_short=typer_instance.pretty_errors_short,334+ pretty_exceptions_short=typer_instance.pretty_exceptions_short,335 rich_markup_mode=typer_instance.rich_markup_mode,336 )337 return group338 23 unmodified lines362 single_command.context_settings = typer_instance.info.context_settings363 364 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 lines471 472 def 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_instance1 unmodified line481 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_group18 unmodified lines516 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 lines559 560 def 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 lines583 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 lines658 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 lines671 if param.name:672 use_params[param.name] = param.default673 674 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 linesmodified:typer/models.py+6 added-6 removed
481 unmodified lines482 class 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_shortmodified:mkdocs.yml+1 added
77 unmodified lines78 - 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.md46 unmodified lines