search
HomeBackend DevelopmentPython TutorialDebugging Savior! Leveraging ObjWatch for Efficient Code Comprehension and Debugging in Complex Python Projects

Source Code Link

Debugging Savior! Leveraging ObjWatch for Efficient Code Comprehension and Debugging in Complex Python Projects aeeeeeep / objwatch

?️ ObjWatch is a Python library to trace and monitor object attributes and method calls.

ObjWatch

Debugging Savior! Leveraging ObjWatch for Efficient Code Comprehension and Debugging in Complex Python Projects Debugging Savior! Leveraging ObjWatch for Efficient Code Comprehension and Debugging in Complex Python Projects Debugging Savior! Leveraging ObjWatch for Efficient Code Comprehension and Debugging in Complex Python Projects Debugging Savior! Leveraging ObjWatch for Efficient Code Comprehension and Debugging in Complex Python Projects Debugging Savior! Leveraging ObjWatch for Efficient Code Comprehension and Debugging in Complex Python Projects

[ English | 中文 ]

Overview

ObjWatch is a robust Python library designed to streamline the debugging and monitoring of complex projects. By offering real-time tracing of object attributes and method calls, ObjWatch empowers developers to gain deeper insights into their codebases, facilitating issue identification, performance optimization, and overall code quality enhancement.

⚠️ Performance Warning

ObjWatch may impact your application's performance. It is recommended to use it solely in debugging environments.

Features

  • Nested Structure Tracing: Visualize and monitor nested function calls and object interactions with clear, hierarchical logging.

  • Enhanced Logging Support: Leverage Python's built-in logging module for structured, customizable log outputs, including support for simple and detailed formats. Additionally, to ensure logs are captured even if the logger is disabled or removed by external libraries, you can set level="force". When level is set to "force", ObjWatch bypasses the standard logging handlers and uses print() to…

View on GitHub

Current Debugging Pain Points

When reading and debugging complex projects, it's common to encounter nested calls with up to a dozen layers, making it difficult to determine the order of execution. The most frustrating aspect is debugging in a multi-process environment; debugging a single process often causes other processes to wait and time out, requiring constant restarting of the debugging program. Using print statements frequently results in missed function calls, which is time-consuming and laborious. Currently, there hasn't been a debugging library that combines simplicity and comprehensiveness, so I spent a weekend developing a tool that addresses this pain point.

What is ObjWatch?

ObjWatch is designed specifically to simplify debugging and monitoring of complex projects. It provides real-time tracking of object properties and method calls, and allows for custom hooks to help developers gain deeper insights into the codebase.

Quick Usage Example

You can install it directly using pip install objwatch. For demonstration purposes, you need to clone the source code:

git clone https://github.com/aeeeeeep/objwatch
cd objwatch
pip install .
python3 examples/example_usage.py

Executing the above code will produce the following call information:

[2025-01-04 19:15:13] [DEBUG] objwatch: Processed targets:
>>>>>>>>>>
examples/example_usage.py
 None
[2025-01-04 19:15:13] [DEBUG] objwatch: | run SampleClass.increment  10
[2025-01-04 19:15:13] [DEBUG] objwatch: | | upd SampleClass.value 10 -> 11
[2025-01-04 19:15:13] [DEBUG] objwatch: | end SampleClass.increment -> None
[2025-01-04 19:15:13] [DEBUG] objwatch: | run SampleClass.increment  12
[2025-01-04 19:15:13] [DEBUG] objwatch: | end SampleClass.increment -> None
[2025-01-04 19:15:13] [DEBUG] objwatch: | run SampleClass.increment  13
[2025-01-04 19:15:13] [DEBUG] objwatch: | end SampleClass.increment -> None
[2025-01-04 19:15:13] [DEBUG] objwatch: | run SampleClass.increment  14
[2025-01-04 19:15:13] [DEBUG] objwatch: | end SampleClass.increment -> None
[2025-01-04 19:15:13] [DEBUG] objwatch: | run SampleClass.increment  15
[2025-01-04 19:15:13] [DEBUG] objwatch: | end SampleClass.increment -> None
[2025-01-04 19:15:13] [DEBUG] objwatch: | run SampleClass.decrement  14
[2025-01-04 19:15:13] [DEBUG] objwatch: | end SampleClass.decrement -> None
[2025-01-04 19:15:13] [DEBUG] objwatch: | run SampleClass.decrement  13
[2025-01-04 19:15:13] [DEBUG] objwatch: | end SampleClass.decrement -> None
[2025-01-04 19:15:13] [DEBUG] objwatch: | run SampleClass.decrement  12
[2025-01-04 19:15:13] [DEBUG] objwatch: | end SampleClass.decrement -> None
[2025-01-04 19:15:13] [DEBUG] objwatch: end main -> None
[2025-01-04 19:15:13] [INFO] objwatch: Stopping ObjWatch tracing.
[2025-01-04 19:15:13] [INFO] objwatch: Stopping tracing.

The most crucial part of the code is the following:

# Using as a Context Manager with Detailed Logging
with objwatch.ObjWatch(['examples/example_usage.py']):
    main()

# Using the API with Simple Logging
obj_watch = objwatch.watch(['examples/example_usage.py'])
main()
obj_watch.stop()

We can use the tool both through a context manager and via API calls. In the example, we specify tracking for the examples/example_usage.py file, meaning that any function, method, or variable within examples/example_usage.py will be logged by the tool. This clear, hierarchical logging helps visualize and monitor nested function calls and object interactions. The printed logs include the following types of execution:

  • run: Indicates the start of a function or class method execution.
  • end: Signifies the end of a function or class method execution.
  • upd: Represents the creation of a new variable.
  • apd: Denotes the addition of elements to data structures like lists, sets, or dictionaries.
  • pop: Marks the removal of elements from data structures like lists, sets, or dictionaries.

The example is relatively simple, but this functionality will be extremely useful for executing large-scale projects.

Overall Features

ObjWatch provides the following interfaces:

  • targets (list): Files or modules to monitor.
  • exclude_targets (list, optional): Files or modules to exclude from monitoring.
  • ranks (list, optional): GPU ranks to track when using torch.distributed.
  • output (str, optional): Path to a file for writing logs.
  • output_xml (str, optional): Path to the XML file for writing structured logs. If specified, tracing information will be saved in a nested XML format for easy browsing and analysis.
  • level (str, optional): Logging level (e.g., logging.DEBUG, logging.INFO, force etc.).
  • simple (bool, optional): Enable simple logging mode with the format "DEBUG: {msg}".
  • wrapper (FunctionWrapper, optional): Custom wrapper to extend tracing and logging functionality.
  • with_locals (bool, optional): Enable tracing and logging of local variables within functions during their execution.
  • with_module_path (bool, optional): Control whether to prepend the module path to function names in logs.

Key Feature: Custom Wrapper Extensions

ObjWatch provides the FunctionWrapper abstract base class, allowing users to create custom wrappers to extend and customize the library's tracking and logging functionality. By inheriting from FunctionWrapper, developers can implement customized behaviors tailored to specific project requirements. These behaviors will be executed during function calls and returns, providing more professional monitoring.

FunctionWrapper Class

The FunctionWrapper class defines two core methods that must be implemented:

  • wrap_call(self, func_name: str, frame: FrameType) -> str:

This method is invoked at the beginning of a function call. It receives the function name and the current frame object, which contains the execution context, including local variables and the call stack. Implement this method to extract, log, or modify information before the function executes.

  • wrap_return(self, func_name: str, result: Any) -> str:

This method is called upon a function's return. It receives the function name and the result returned by the function. Use this method to log, analyze, or alter information after the function has completed execution.

  • wrap_upd(self, old_value: Any, current_value: Any) -> Tuple[str, str]:

This method is triggered when a variable is updated, receiving the old value and the current value. It can be used to log changes to variables, allowing for the tracking and debugging of variable state transitions.

For more details on frame objects, refer to the official Python documentation.

TensorShapeLogger

This is an example of a custom wrapper I implemented based on my usage scenario. The code is in the objwatch/wrappers.py file. This wrapper automatically records the tensor shapes of inputs and outputs in all function method calls within the specified module, as well as the states of variables. This is extremely useful for understanding the execution logic of complex distributed frameworks.

git clone https://github.com/aeeeeeep/objwatch
cd objwatch
pip install .
python3 examples/example_usage.py

In deep learning projects, the shape and dimensions of tensors are crucial. A small dimension error can prevent the entire model from training or predicting correctly. Manually checking each tensor's shape is tedious and error-prone. The TensorShapeLogger automates the recording of tensor shapes, helping developers to:

  • Quickly identify dimension mismatch issues: Automatically records shape information to promptly detect and fix dimension errors.
  • Optimize model architecture: By tracking the changes in tensor shapes, optimize the network structure to improve model performance.
  • Increase debugging efficiency: Reduce the time spent manually checking tensor shapes, allowing focus on core model development.

Example of Using a Custom Wrapper

It is recommended to refer to the tests/test_torch_train.py file. This file contains a complete example of a PyTorch training process, demonstrating how to integrate ObjWatch for monitoring and logging.

Notes

⚠️ Performance Warning
ObjWatch can impact the performance of your program when used in a debugging environment. Therefore, it is recommended to use it only during the debugging and development phases.

This is just an initial write-up; I plan to add more over time. If you find it useful, feel free to give it a star.

The library is still actively being updated. If you have any questions or suggestions, please leave a comment or open an issue in the repository.

The above is the detailed content of Debugging Savior! Leveraging ObjWatch for Efficient Code Comprehension and Debugging in Complex Python Projects. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Python: Exploring Its Primary ApplicationsPython: Exploring Its Primary ApplicationsApr 10, 2025 am 09:41 AM

Python is widely used in the fields of web development, data science, machine learning, automation and scripting. 1) In web development, Django and Flask frameworks simplify the development process. 2) In the fields of data science and machine learning, NumPy, Pandas, Scikit-learn and TensorFlow libraries provide strong support. 3) In terms of automation and scripting, Python is suitable for tasks such as automated testing and system management.

How Much Python Can You Learn in 2 Hours?How Much Python Can You Learn in 2 Hours?Apr 09, 2025 pm 04:33 PM

You can learn the basics of Python within two hours. 1. Learn variables and data types, 2. Master control structures such as if statements and loops, 3. Understand the definition and use of functions. These will help you start writing simple Python programs.

How to teach computer novice programming basics in project and problem-driven methods within 10 hours?How to teach computer novice programming basics in project and problem-driven methods within 10 hours?Apr 02, 2025 am 07:18 AM

How to teach computer novice programming basics within 10 hours? If you only have 10 hours to teach computer novice some programming knowledge, what would you choose to teach...

How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading?How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading?Apr 02, 2025 am 07:15 AM

How to avoid being detected when using FiddlerEverywhere for man-in-the-middle readings When you use FiddlerEverywhere...

What should I do if the '__builtin__' module is not found when loading the Pickle file in Python 3.6?What should I do if the '__builtin__' module is not found when loading the Pickle file in Python 3.6?Apr 02, 2025 am 07:12 AM

Error loading Pickle file in Python 3.6 environment: ModuleNotFoundError:Nomodulenamed...

How to improve the accuracy of jieba word segmentation in scenic spot comment analysis?How to improve the accuracy of jieba word segmentation in scenic spot comment analysis?Apr 02, 2025 am 07:09 AM

How to solve the problem of Jieba word segmentation in scenic spot comment analysis? When we are conducting scenic spot comments and analysis, we often use the jieba word segmentation tool to process the text...

How to use regular expression to match the first closed tag and stop?How to use regular expression to match the first closed tag and stop?Apr 02, 2025 am 07:06 AM

How to use regular expression to match the first closed tag and stop? When dealing with HTML or other markup languages, regular expressions are often required to...

How to get news data bypassing Investing.com's anti-crawler mechanism?How to get news data bypassing Investing.com's anti-crawler mechanism?Apr 02, 2025 am 07:03 AM

Understanding the anti-crawling strategy of Investing.com Many people often try to crawl news data from Investing.com (https://cn.investing.com/news/latest-news)...

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use