Skip to content

Commit 01daccf

Browse files
miss-islingtoniritkatrielAlexWaygood
authored
[3.12] gh-71784: [doc] add usage examples for traceback.TracebackException (GH-125189) (#125248)
Co-authored-by: Irit Katriel <[email protected]> Co-authored-by: Alex Waygood <[email protected]>
1 parent 01d9a89 commit 01daccf

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

@@ -230,20 +247,24 @@ The module defines the following functions:
230247

231248
.. versionadded:: 3.5
232249

233-
The module also defines the following classes:
234250

235251
:class:`!TracebackException` Objects
236252
------------------------------------
237253

238254
.. versionadded:: 3.5
239255

240256
:class:`!TracebackException` objects are created from actual exceptions to
241-
capture data for later printing in a lightweight fashion.
257+
capture data for later printing. They offer a more lightweight method of
258+
storing this information by avoiding holding references to
259+
:ref:`traceback<traceback-objects>` and :ref:`frame<frame-objects>` objects
260+
In addition, they expose more options to configure the output compared to
261+
the module-level functions described above.
242262

243263
.. 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)
244264

245-
Capture an exception for later rendering. *limit*, *lookup_lines* and
246-
*capture_locals* are as for the :class:`StackSummary` class.
265+
Capture an exception for later rendering. The meaning of *limit*,
266+
*lookup_lines* and *capture_locals* are as for the :class:`StackSummary`
267+
class.
247268

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

489510
.. _traceback-example:
490511

491-
Traceback Examples
492-
------------------
512+
Examples of Using the Module-Level Functions
513+
--------------------------------------------
493514

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

529550
try:
530551
lumberjack()
531-
except IndexError:
532-
exc = sys.exception()
552+
except IndexError as exc:
533553
print("*** print_tb:")
534554
traceback.print_tb(exc.__traceback__, limit=1, file=sys.stdout)
535555
print("*** print_exception:")
@@ -627,5 +647,88 @@ This last example demonstrates the final few formatting functions:
627647
[' File "spam.py", line 3, in <module>\n spam.eggs()\n',
628648
' File "eggs.py", line 42, in eggs\n return "bacon"\n']
629649
>>> an_error = IndexError('tuple index out of range')
630-
>>> traceback.format_exception_only(type(an_error), an_error)
650+
>>> traceback.format_exception_only(an_error)
631651
['IndexError: tuple index out of range\n']
652+
653+
654+
Examples of Using :class:`TracebackException`
655+
---------------------------------------------
656+
657+
With the helper class, we have more options::
658+
659+
>>> import sys
660+
>>> from traceback import TracebackException
661+
>>>
662+
>>> def lumberjack():
663+
... bright_side_of_life()
664+
...
665+
>>> def bright_side_of_life():
666+
... t = "bright", "side", "of", "life"
667+
... return t[5]
668+
...
669+
>>> try:
670+
... lumberjack()
671+
... except IndexError as e:
672+
... exc = e
673+
...
674+
>>> try:
675+
... try:
676+
... lumberjack()
677+
... except:
678+
... 1/0
679+
... except Exception as e:
680+
... chained_exc = e
681+
...
682+
>>> # limit works as with the module-level functions
683+
>>> TracebackException.from_exception(exc, limit=-2).print()
684+
Traceback (most recent call last):
685+
File "<python-input-1>", line 6, in lumberjack
686+
bright_side_of_life()
687+
~~~~~~~~~~~~~~~~~~~^^
688+
File "<python-input-1>", line 10, in bright_side_of_life
689+
return t[5]
690+
~^^^
691+
IndexError: tuple index out of range
692+
693+
>>> # capture_locals adds local variables in frames
694+
>>> TracebackException.from_exception(exc, limit=-2, capture_locals=True).print()
695+
Traceback (most recent call last):
696+
File "<python-input-1>", line 6, in lumberjack
697+
bright_side_of_life()
698+
~~~~~~~~~~~~~~~~~~~^^
699+
File "<python-input-1>", line 10, in bright_side_of_life
700+
return t[5]
701+
~^^^
702+
t = ("bright", "side", "of", "life")
703+
IndexError: tuple index out of range
704+
705+
>>> # The *chain* kwarg to print() controls whether chained
706+
>>> # exceptions are displayed
707+
>>> TracebackException.from_exception(chained_exc).print()
708+
Traceback (most recent call last):
709+
File "<python-input-19>", line 4, in <module>
710+
lumberjack()
711+
~~~~~~~~~~^^
712+
File "<python-input-8>", line 7, in lumberjack
713+
bright_side_of_life()
714+
~~~~~~~~~~~~~~~~~~~^^
715+
File "<python-input-8>", line 11, in bright_side_of_life
716+
return t[5]
717+
~^^^
718+
IndexError: tuple index out of range
719+
720+
During handling of the above exception, another exception occurred:
721+
722+
Traceback (most recent call last):
723+
File "<python-input-19>", line 6, in <module>
724+
1/0
725+
~^~
726+
ZeroDivisionError: division by zero
727+
728+
>>> TracebackException.from_exception(chained_exc).print(chain=False)
729+
Traceback (most recent call last):
730+
File "<python-input-19>", line 6, in <module>
731+
1/0
732+
~^~
733+
ZeroDivisionError: division by zero
734+

0 commit comments

Comments
 (0)