Skip to content

Commit f9ae5d1

Browse files
gh-71784: [doc] add usage examples for traceback.TracebackException (#125189)
Co-authored-by: Alex Waygood <[email protected]>
1 parent 82dfdc3 commit f9ae5d1

File tree

1 file changed

+118
-15
lines changed

1 file changed

+118
-15
lines changed

Doc/library/traceback.rst

Lines changed: 118 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -8,11 +8,15 @@
88

99
--------------
1010

11-
This module provides a standard interface to extract, format and print stack
12-
traces of Python programs. It exactly mimics the behavior of the Python
13-
interpreter when it prints a stack trace. This is useful when you want to print
14-
stack traces under program control, such as in a "wrapper" around the
15-
interpreter.
11+
This module provides a standard interface to extract, format and print
12+
stack traces of Python programs. It is more flexible than the
13+
interpreter's default traceback display, and therefore makes it
14+
possible to configure certain aspects of the output. Finally,
15+
it contains a utility for capturing enough information about an
16+
exception to print it later, without the need to save a reference
17+
to the actual exception. Since exceptions can be the roots of large
18+
objects graph, this utility can significantly improve
19+
memory management.
1620

1721
.. index:: pair: object; traceback
1822

@@ -29,7 +33,20 @@ which are assigned to the :attr:`~BaseException.__traceback__` field of
2933
Module :mod:`pdb`
3034
Interactive source code debugger for Python programs.
3135

32-
The module defines the following functions:
36+
The module's API can be divided into two parts:
37+
38+
* Module-level functions offering basic functionality, which are useful for interactive
39+
inspection of exceptions and tracebacks.
40+
41+
* :class:`TracebackException` class and its helper classes
42+
:class:`StackSummary` and :class:`FrameSummary`. These offer both more
43+
flexibility in the output generated and the ability to store the information
44+
necessary for later formatting without holding references to actual exception
45+
and traceback objects.
46+
47+
48+
Module-Level Functions
49+
----------------------
3350

3451
.. function:: print_tb(tb, limit=None, file=None)
3552

@@ -237,20 +254,24 @@ The module defines the following functions:
237254

238255
.. versionadded:: 3.5
239256

240-
The module also defines the following classes:
241257

242258
:class:`!TracebackException` Objects
243259
------------------------------------
244260

245261
.. versionadded:: 3.5
246262

247263
:class:`!TracebackException` objects are created from actual exceptions to
248-
capture data for later printing in a lightweight fashion.
264+
capture data for later printing. They offer a more lightweight method of
265+
storing this information by avoiding holding references to
266+
:ref:`traceback<traceback-objects>` and :ref:`frame<frame-objects>` objects
267+
In addition, they expose more options to configure the output compared to
268+
the module-level functions described above.
249269

250270
.. class:: TracebackException(exc_type, exc_value, exc_traceback, *, limit=None, lookup_lines=True, capture_locals=False, compact=False, max_group_width=15, max_group_depth=10)
251271

252-
Capture an exception for later rendering. *limit*, *lookup_lines* and
253-
*capture_locals* are as for the :class:`StackSummary` class.
272+
Capture an exception for later rendering. The meaning of *limit*,
273+
*lookup_lines* and *capture_locals* are as for the :class:`StackSummary`
274+
class.
254275

255276
If *compact* is true, only data that is required by
256277
:class:`!TracebackException`'s :meth:`format` method
@@ -509,8 +530,8 @@ in a :ref:`traceback <traceback-objects>`.
509530

510531
.. _traceback-example:
511532

512-
Traceback Examples
513-
------------------
533+
Examples of Using the Module-Level Functions
534+
--------------------------------------------
514535

515536
This simple example implements a basic read-eval-print loop, similar to (but
516537
less useful than) the standard Python interactive interpreter loop. For a more
@@ -549,8 +570,7 @@ exception and traceback:
549570

550571
try:
551572
lumberjack()
552-
except IndexError:
553-
exc = sys.exception()
573+
except IndexError as exc:
554574
print("*** print_tb:")
555575
traceback.print_tb(exc.__traceback__, limit=1, file=sys.stdout)
556576
print("*** print_exception:")
@@ -653,5 +673,88 @@ This last example demonstrates the final few formatting functions:
653673
[' File "spam.py", line 3, in <module>\n spam.eggs()\n',
654674
' File "eggs.py", line 42, in eggs\n return "bacon"\n']
655675
>>> an_error = IndexError('tuple index out of range')
656-
>>> traceback.format_exception_only(type(an_error), an_error)
676+
>>> traceback.format_exception_only(an_error)
657677
['IndexError: tuple index out of range\n']
678+
679+
680+
Examples of Using :class:`TracebackException`
681+
---------------------------------------------
682+
683+
With the helper class, we have more options::
684+
685+
>>> import sys
686+
>>> from traceback import TracebackException
687+
>>>
688+
>>> def lumberjack():
689+
... bright_side_of_life()
690+
...
691+
>>> def bright_side_of_life():
692+
... t = "bright", "side", "of", "life"
693+
... return t[5]
694+
...
695+
>>> try:
696+
... lumberjack()
697+
... except IndexError as e:
698+
... exc = e
699+
...
700+
>>> try:
701+
... try:
702+
... lumberjack()
703+
... except:
704+
... 1/0
705+
... except Exception as e:
706+
... chained_exc = e
707+
...
708+
>>> # limit works as with the module-level functions
709+
>>> TracebackException.from_exception(exc, limit=-2).print()
710+
Traceback (most recent call last):
711+
File "<python-input-1>", line 6, in lumberjack
712+
bright_side_of_life()
713+
~~~~~~~~~~~~~~~~~~~^^
714+
File "<python-input-1>", line 10, in bright_side_of_life
715+
return t[5]
716+
~^^^
717+
IndexError: tuple index out of range
718+
719+
>>> # capture_locals adds local variables in frames
720+
>>> TracebackException.from_exception(exc, limit=-2, capture_locals=True).print()
721+
Traceback (most recent call last):
722+
File "<python-input-1>", line 6, in lumberjack
723+
bright_side_of_life()
724+
~~~~~~~~~~~~~~~~~~~^^
725+
File "<python-input-1>", line 10, in bright_side_of_life
726+
return t[5]
727+
~^^^
728+
t = ("bright", "side", "of", "life")
729+
IndexError: tuple index out of range
730+
731+
>>> # The *chain* kwarg to print() controls whether chained
732+
>>> # exceptions are displayed
733+
>>> TracebackException.from_exception(chained_exc).print()
734+
Traceback (most recent call last):
735+
File "<python-input-19>", line 4, in <module>
736+
lumberjack()
737+
~~~~~~~~~~^^
738+
File "<python-input-8>", line 7, in lumberjack
739+
bright_side_of_life()
740+
~~~~~~~~~~~~~~~~~~~^^
741+
File "<python-input-8>", line 11, in bright_side_of_life
742+
return t[5]
743+
~^^^
744+
IndexError: tuple index out of range
745+
746+
During handling of the above exception, another exception occurred:
747+
748+
Traceback (most recent call last):
749+
File "<python-input-19>", line 6, in <module>
750+
1/0
751+
~^~
752+
ZeroDivisionError: division by zero
753+
754+
>>> TracebackException.from_exception(chained_exc).print(chain=False)
755+
Traceback (most recent call last):
756+
File "<python-input-19>", line 6, in <module>
757+
1/0
758+
~^~
759+
ZeroDivisionError: division by zero
760+

0 commit comments

Comments
 (0)