Table of Contents
Overview
Features
Home Backend Development Python Tutorial 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

Jan 06, 2025 am 02:43 AM

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:

1

2

3

4

git clone https://github.com/aeeeeeep/objwatch

cd objwatch

pip install .

python3 examples/example_usage.py

Copy after login
Copy after login

Executing the above code will produce the following call information:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

[2025-01-04 19:15:13] [DEBUG] objwatch: Processed targets:

>>>>>>>>>>

examples/example_usage.py

<<<<<<<<<<

[2025-01-04 19:15:13] [WARNING] objwatch: wrapper 'BaseLogger' loaded

[2025-01-04 19:15:13] [INFO] objwatch: Starting ObjWatch tracing.

[2025-01-04 19:15:13] [INFO] objwatch: Starting tracing.

[2025-01-04 19:15:13] [DEBUG] objwatch: run main <-

[2025-01-04 19:15:13] [DEBUG] objwatch: | run SampleClass.__init__ <- '0':(type)SampleClass, '1':10

[2025-01-04 19:15:13] [DEBUG] objwatch: | end SampleClass.__init__ -> None

[2025-01-04 19:15:13] [DEBUG] objwatch: | run SampleClass.increment <- '0':(type)SampleClass

[2025-01-04 19:15:13] [DEBUG] objwatch: | | upd SampleClass.value None -> 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 <- '0':(type)SampleClass

[2025-01-04 19:15:13] [DEBUG] objwatch: | | upd SampleClass.value 11 -> 12

[2025-01-04 19:15:13] [DEBUG] objwatch: | end SampleClass.increment -> None

[2025-01-04 19:15:13] [DEBUG] objwatch: | run SampleClass.increment <- '0':(type)SampleClass

[2025-01-04 19:15:13] [DEBUG] objwatch: | | upd SampleClass.value 12 -> 13

[2025-01-04 19:15:13] [DEBUG] objwatch: | end SampleClass.increment -> None

[2025-01-04 19:15:13] [DEBUG] objwatch: | run SampleClass.increment <- '0':(type)SampleClass

[2025-01-04 19:15:13] [DEBUG] objwatch: | | upd SampleClass.value 13 -> 14

[2025-01-04 19:15:13] [DEBUG] objwatch: | end SampleClass.increment -> None

[2025-01-04 19:15:13] [DEBUG] objwatch: | run SampleClass.increment <- '0':(type)SampleClass

[2025-01-04 19:15:13] [DEBUG] objwatch: | | upd SampleClass.value 14 -> 15

[2025-01-04 19:15:13] [DEBUG] objwatch: | end SampleClass.increment -> None

[2025-01-04 19:15:13] [DEBUG] objwatch: | run SampleClass.decrement <- '0':(type)SampleClass

[2025-01-04 19:15:13] [DEBUG] objwatch: | | upd SampleClass.value 15 -> 14

[2025-01-04 19:15:13] [DEBUG] objwatch: | end SampleClass.decrement -> None

[2025-01-04 19:15:13] [DEBUG] objwatch: | run SampleClass.decrement <- '0':(type)SampleClass

[2025-01-04 19:15:13] [DEBUG] objwatch: | | upd SampleClass.value 14 -> 13

[2025-01-04 19:15:13] [DEBUG] objwatch: | end SampleClass.decrement -> None

[2025-01-04 19:15:13] [DEBUG] objwatch: | run SampleClass.decrement <- '0':(type)SampleClass

[2025-01-04 19:15:13] [DEBUG] objwatch: | | upd SampleClass.value 13 -> 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.

Copy after login

The most crucial part of the code is the following:

1

2

3

4

5

6

7

8

# 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()

Copy after login

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.

1

2

3

4

git clone https://github.com/aeeeeeep/objwatch

cd objwatch

pip install .

python3 examples/example_usage.py

Copy after login
Copy after login

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 of this Website
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

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1655
14
PHP Tutorial
1252
29
C# Tutorial
1226
24
Python vs. C  : Applications and Use Cases Compared Python vs. C : Applications and Use Cases Compared Apr 12, 2025 am 12:01 AM

Python is suitable for data science, web development and automation tasks, while C is suitable for system programming, game development and embedded systems. Python is known for its simplicity and powerful ecosystem, while C is known for its high performance and underlying control capabilities.

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.

Python: Games, GUIs, and More Python: Games, GUIs, and More Apr 13, 2025 am 12:14 AM

Python excels in gaming and GUI development. 1) Game development uses Pygame, providing drawing, audio and other functions, which are suitable for creating 2D games. 2) GUI development can choose Tkinter or PyQt. Tkinter is simple and easy to use, PyQt has rich functions and is suitable for professional development.

The 2-Hour Python Plan: A Realistic Approach The 2-Hour Python Plan: A Realistic Approach Apr 11, 2025 am 12:04 AM

You can learn basic programming concepts and skills of Python within 2 hours. 1. Learn variables and data types, 2. Master control flow (conditional statements and loops), 3. Understand the definition and use of functions, 4. Quickly get started with Python programming through simple examples and code snippets.

Python vs. C  : Learning Curves and Ease of Use Python vs. C : Learning Curves and Ease of Use Apr 19, 2025 am 12:20 AM

Python is easier to learn and use, while C is more powerful but complex. 1. Python syntax is concise and suitable for beginners. Dynamic typing and automatic memory management make it easy to use, but may cause runtime errors. 2.C provides low-level control and advanced features, suitable for high-performance applications, but has a high learning threshold and requires manual memory and type safety management.

Python: Exploring Its Primary Applications Python: Exploring Its Primary Applications Apr 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.

Python and Time: Making the Most of Your Study Time Python and Time: Making the Most of Your Study Time Apr 14, 2025 am 12:02 AM

To maximize the efficiency of learning Python in a limited time, you can use Python's datetime, time, and schedule modules. 1. The datetime module is used to record and plan learning time. 2. The time module helps to set study and rest time. 3. The schedule module automatically arranges weekly learning tasks.

Python: Automation, Scripting, and Task Management Python: Automation, Scripting, and Task Management Apr 16, 2025 am 12:14 AM

Python excels in automation, scripting, and task management. 1) Automation: File backup is realized through standard libraries such as os and shutil. 2) Script writing: Use the psutil library to monitor system resources. 3) Task management: Use the schedule library to schedule tasks. Python's ease of use and rich library support makes it the preferred tool in these areas.

See all articles