What is the traceback.print_tb() function in Python?
Overview
The traceback module in Python provides a standardized interface to extract, format, and print stacktraces.
The print_tb method of the traceback module prints the stacktraces from the traceback object up to a limit.
Syntax
Here’s the syntax for traceback.print_tb() method:
traceback.print_tb(tb, limit=None, file=None)
Parameters
Here are the parameters of the traceback.print_tb() method:
tb: This is the traceback object.limit: This parameter can be used to specify the amount of trace required. The default value isNoneand will print the whole stacktrace. Whenlimitis a negative value, theabs(limit)is taken into consideration.file: This parameter indicates where the stacktrace output should be directed to. The default value isNoneand the output goes to the standard error.
Example
import tracebackdef func_2():print("hello educative")raise Exception("")def func_1():func_2()print("Printing complete stacktrace:")try:func_1()except Exception as e:traceback.print_tb(e.__traceback__)print("-" * 8)print("Printing upto 2 stacktraces:")try:func_1()except Exception as e:traceback.print_tb(e.__traceback__, limit=2)
Explanation
- Line 1: We import the
tracebackmodule. - Lines 3–5: The
func_2()function is defined where it throws an exception. - Lines 7–8: The
func_1()function is defined. This invokesfunc_2(). - Lines 11–14:
func_1()is invoked, and the complete stacktrace is printed. - Lines 18–21:
func_1()is invoked, and the stacktrace up to level 2 is printed. We do this using thelimitparameter of theprint_tb()function.
Free Resources
Copyright ©2025 Educative, Inc. All rights reserved