Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Python Variables
Next article icon

Python – sys.settrace()

Last Updated : 21 Apr, 2020
Comments
Improve
Suggest changes
Like Article
Like
Report

Python sys module provides some of the powerful functions but they are complex to understand. One of which is the sys.settrace() which is used for implementing debuggers, profilers and coverage tools. This is thread-specific and must register the trace using threading.settrace().

Knowing how the function works internally is really important in case you are planning to create your own debugger.

On a higher level, sys.settrace() registers the traceback to the Python interpreter. A traceback is basically the information that is returned when an event happens in the code. You might have seen traceback when your code has some error or an exception is raised.

The registered traceback is invoked when one of the following four events occur :

  1. Function is called
  2. Function returns
  3. Execution of a line
  4. Exception is raised

Syntax: sys.settrace(frame, event, arg.frame)

Parameters:
frame: frame is the current stack frame
event: A string which be either 'call', 'line', 'return', 'exception' or 'opcode'
arg: Depends on the event type

Returns: Reference to the local trace function which then returns reference to itself.

Example:

Let’s create our own local trace function with line, function and call events. These events are highlighted in the below given code.




# program to display the functioning of
# settrace()
from sys import settrace
  
  
# local trace function which returns itself
def my_tracer(frame, event, arg = None):
    # extracts frame code
    code = frame.f_code
  
    # extracts calling function name
    func_name = code.co_name
  
    # extracts the line number
    line_no = frame.f_lineno
  
    print(f"A {event} encountered in \
    {func_name}() at line number {line_no} ")
  
    return my_tracer
  
  
# global trace function is invoked here and
# local trace function is set for fun()
def fun():
    return "GFG"
  
  
# global trace function is invoked here and
# local trace function is set for check()
def check():
    return fun()
  
  
# returns reference to local
# trace function (my_tracer)
settrace(my_tracer)
  
check()
 
 

Output:

  A call encountered in check() at line number 30   A line encountered in check() at line number 31   A call encountered in fun() at line number 24   A line encountered in fun() at line number 25   A return encountered in fun() at line number 25   A return encountered in check() at line number 31   

You might be wondering why does the local function my_code returns itself?
The reason is hidden in the functioning of sys.settrace(). What sys.settrace does is that it first registers a global trace which is called whenever a frame is created which returns our local trace function my_trace whenever any one of the above mentioned event occurs. For better understanding look at the image shown below:

Working-of-settrace-python

If we don’t want our scope to be traced then None should be returned but if that is not the case we might want to do the same with our local trace function then it should return None else if there is an error then settrace(None) is automatically called.

Note : There is a function named gettrace available in sys module to get the trace set by sys.settrace()



Next Article
Python Variables
author
nishkarsh146
Improve
Article Tags :
  • Python
  • python-modules
Practice Tags :
  • python

Similar Reads

  • Python Traceback
    In Python, A traceback is a report containing the function calls made in your code at a specific point i.e when you get an error it is recommended that you should trace it backward(traceback). Whenever the code gets an exception, the traceback will give the information about what went wrong in the c
    4 min read
  • Python - sys.stdout.flush()
    A data buffer is a region of physical memory storage used to temporarily store data while it is being moved from one place to another. The data is stored in a buffer as it is retrieved from an input device or just before it is sent to an output device or when moving data between processes within a c
    3 min read
  • Python | sys.setswitchinterval() method
    This sys module provides access to some variables used or maintained by the interpreter and to functions that interact strongly with the interpreter. It provides information about constants, functions and methods of python interpreter. It can be used for manipulating Python runtime environment. sys.
    2 min read
  • Traceback in Python
    Traceback is a python module that provides a standard interface to extract, format and print stack traces of a python program. When it prints the stack trace it exactly mimics the behaviour of a python interpreter. Useful when you want to print the stack trace at any step. They are usually seen when
    8 min read
  • Python Variables
    In Python, variables are used to store data that can be referenced and manipulated during program execution. A variable is essentially a name that is assigned to a value. Unlike many other programming languages, Python variables do not require explicit declaration of type. The type of the variable i
    7 min read
  • sys.stdout.write in Python
    sys.stdout.write() is a built-in Python method that writes output directly to the console without automatically adding a newline (\n). It is part of the sys module and requires import sys before use. Unlike print(), it does not insert spaces between multiple arguments, allowing precise control over
    3 min read
  • Python | sympy.sec() method
    With the help of sympy.sec() method, we are able to find the value of sec theta using sympy.sec() function. Syntax : sympy.sec() Return : Return value of sec theta. Example #1 : In this example we can see that by using sympy.sec() method, we can find the value of sec theta. # import sympy from sympy
    1 min read
  • Python Testing
    Python testing is a fundamental aspect of software development that plays a crucial role in ensuring the reliability, correctness, and maintainability of your code. By adopting effective testing strategies, leveraging robust testing frameworks, and adhering to best practices, you can build high-qual
    15 min read
  • Python subprocess module
    The subprocess module present in Python(both 2.x and 3.x) is used to run new applications or programs through Python code by creating new processes. It also helps to obtain the input/output/error pipes as well as the exit codes of various commands. In this tutorial, we’ll delve into how to effective
    9 min read
  • Python | sys.setrecursionlimit() method
    This sys module provides access to some variables used or maintained by the interpreter and to functions that interact strongly with the interpreter. It provides information about constants, functions and methods of python interpreter. It can be used for manipulating Python runtime environment. sys.
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences