PySnooper

repository·master·Indexed 12 days ago

https://github.com/cool-rr/pysnooper

A lightweight debugging tool for Python that provides a play-by-play log of function execution, including line execution and local variable changes. It can be used as a decorator via @pysnooper.snoop() or as a context manager to trace specific code blocks.

Tokens
690
Snippets
4
Records
4
Agent score
47%

What's inside PySnooper

  1. Trace a function with @pysnooper.snoop()

    master

    To trace the execution of an entire function, apply the @pysnooper.snoop() decorator to the function definition. This will log which lines are executed and when local variables change to stderr by default.

    import pysnooper
    
    @pysnooper.snoop()
    def number_to_bits(number):
        if number:
            bits = []
            while number:
                number, remainder = divmod(number, 2)
                bits.insert(0, remainder)
            return bits
        else:
            return [0]
    
    number_to_bits(6)
  2. Trace a specific code block with pysnooper.snoop()

    master

    If you do not want to trace an entire function, you can use pysnooper.snoop() as a context manager with a with block to trace only the relevant section of code.

    import pysnooper
    import random
    
    def foo():
        lst = []
        for i in range(10):
            lst.append(random.randrange(1, 1000))
    
        with pysnooper.snoop():
            lower = min(lst)
            upper = max(lst)
            mid = (lower + upper) / 2
            print(lower, mid, upper)
    
    foo()
  3. Configure PySnooper output and tracing behavior

    master

    The @pysnooper.snoop() decorator accepts several arguments to customize the debugging output:

    • Output Redirection: Pass a file path as the first argument to redirect logs to a file instead of stderr. You can also pass a stream or a callable.
    • watch: A tuple of strings representing expressions (e.g., attributes or dictionary keys) that you want to monitor even if they aren't local variables.
    • depth: An integer specifying how many levels of function calls to trace. Setting depth=2 will show snoop lines for functions called by your decorated function.
    # Redirect output to a file
    @pysnooper.snoop('/my/log/file.log')
    
    # Watch specific expressions
    @pysnooper.snoop(watch=('foo.bar', 'self.x["whatever"]'))
    
    # Trace nested function calls
    @pysnooper.snoop(depth=2)