Featured image of post Still Debugging with print? Try PySnooper

Still Debugging with print? Try PySnooper

An introduction to PySnooper, a Python code debugging tool

Why Do You Need PySnooper?

During Python development, print debugging and breakpoint debugging are the most commonly used debugging methods. But when facing complex logic, traditional methods have clear shortcomings:

  • print statements must be added and removed manually, cluttering the code
  • IDE breakpoint debugging is hard to use in remote-server scenarios
  • Debugging multithreaded/asynchronous scenarios is difficult

Through an intelligent logging mechanism, PySnooper enables zero-intrusion debugging, offering another intuitive and convenient way to observe and debug.

Detailed Look at Core Features

1. Intelligent Context Tracking

For example, let’s write a recursive function

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
import pysnooper

@pysnooper.snoop()
def factorial(n):
    if n == 1:
        return 1
    else:
        return n * factorial(n-1)

factorial(3)

Sample output:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
(.venv) C:\Chengxiaqiucao\AI
python ai_test.py
Source path:... C:\Chengxiaqiucao\AI\ai_test.py
Starting var:.. n = 3
20:14:50.353061 call         9 def factorial(n):
20:14:50.357038 line        10     if n == 1:
20:14:50.357103 line        13         return n * factorial(n-1)
    Starting var:.. n = 2
    20:14:50.357159 call         9 def factorial(n):
    20:14:50.357220 line        10     if n == 1:
    20:14:50.357291 line        13         return n * factorial(n-1)
        Starting var:.. n = 1
        20:14:50.357348 call         9 def factorial(n):
        20:14:50.357421 line        10     if n == 1:
        20:14:50.357460 line        11         return 1
        20:14:50.357501 return      11         return 1
        Return value:.. 1
        Elapsed time: 00:00:00.000248
    20:14:50.357716 return      13         return n * factorial(n-1)
    Return value:.. 2
    Elapsed time: 00:00:00.000649
20:14:50.357843 return      13         return n * factorial(n-1)
Return value:.. 6
Elapsed time: 00:00:00.005107

It automatically records the function call stack and code execution path, and supports tracing recursive functions

2. Variable Monitoring

1
2
3
4
5
6
7
@pysnooper.snoop(watch=('result', 'len(data)'))
def process_data(data):
    result = []
    for item in data:
        processed = item * 2
        result.append(processed)
    return sum(result)

Monitoring features:

  • Supports expression monitoring (e.g. len(data))
  • Displays variable types in real time
  • Highlights value changes

3. Context Manager Mode and Output to a File

1
2
3
# Context manager mode
with pysnooper.snoop(output='/var/log/debug.log'):
    critical_operation()

4. Specifying Prefixes for Multiple Trace Points

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
@pysnooper.snoop(prefix='[add]')  
def add(a, b):  
    return a + b  
  
@pysnooper.snoop(prefix='[main]')  
def main():  
    result = add(5, 7)  
    return result  
  
result = main()  
print(f"Final result: {result}")

The output displays the different prefixes you specified

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
[main]20:29:01.818895 call        17 def main():
[main]20:29:01.819578 line        18     result = add(5, 7)
[add]    Source path:... C:\Chengxiaqiucao\AI\ai_test.py
[add]    Starting var:.. a = 5
[add]    Starting var:.. b = 7
[add]    20:29:01.819791 call        13 def add(a, b):
[add]    20:29:01.820558 line        14     return a + b
[add]    20:29:01.820758 return      14     return a + b
[add]    Return value:.. 12
[add]    Elapsed time: 00:00:00.001314
[main]New var:....... result = 12
[main]20:29:01.821253 line        19     return result
[main]20:29:01.821503 return      19     return result
[main]Return value:.. 12
[main]Elapsed time: 00:00:00.002834
Final result: 12

5. Setting the Trace Depth

If the code involves multiple levels of function calls, you can also specify the recording depth, which defaults to 1. Flexibly combining the depth parameter helps us focus on the parts we care about

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
@pysnooper.snoop(depth=1)  
def outer_function(x):  
    return inner_function(x + 1)  
  
@pysnooper.snoop(depth=2)  
def inner_function(y):  
    return y * 2  
  
result = outer_function(10)  
print(f"Outer function result: {result}")

Output:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
Starting var:.. x = 10
20:37:49.360851 call         9 def outer_function(x):
20:37:49.361569 line        10     return inner_function(x + 1)
    Source path:... C:\Chengxiaqiucao\ai\ai_test.py
    Starting var:.. y = 11
    20:37:49.361734 call        13 def inner_function(y):
    20:37:49.362077 line        14     return y * 2
    20:37:49.362184 return      14     return y * 2
    Return value:.. 22
    Elapsed time: 00:00:00.000589
20:37:49.362380 return      10     return inner_function(x + 1)
Return value:.. 22
Elapsed time: 00:00:00.001683
Outer function result: 22

Summary

With this tool, when debugging, especially when testing code on servers, you can monitor runtime variables and execution flow with a single decorator line, leaving the hassle of print debugging behind!

Built with Hugo
Theme Stack designed by Jimmy