API · Python

Python sys.gettrace() Method

The sys.gettrace() is an in-built Python function used to implement the debuggers, coverage tools, and profilers.

On this page

The sys.gettrace() method is an efficient way of getting the traceback call to the platform’s Python interpreter. A traceback call is the information returned when an event occurs in the code.

Syntax of Python sys.gettrace() Method

sys.gettrace()

Parameters

No parameter is required. It is a non-callable object.

Return

The return type of this method is the trace function as set by the sys.settrace() method.

Example Codes: Working With the sys.gettrace() Method

import sys

from sys import settrace


def trace(frame, event, arg):

    code = frame.f_locals["a"]

    if code % 2 == 0:

        frame.f_locals["a"] = code


def f(a):

    print(a)


if __name__ == "__main__":

    sys.settrace(trace)

    for x in range(0, 10):

        f(x)

print(sys.gettrace())

Output:

0
1
2
3
4
5
6
7
8
9
<function trace at 0x7f344f73a280>

In the above code, we modified the arguments sent to a function. The function uses a for loop and counts the digit in a specified range.

After setting the system trace call, we used the sys.gettrace() method to return the traceback call.