DEV Community

qoqosz
qoqosz

Posted on

Python debug function

In Rust you find the dbg! macro that prints to what a given expression evaluates to. This on its own wouldn't be as helpful. Thus, additionally the macro returns the value of the evaluated expression.

It is possible to mimic this functionality in Python. You may find the original implementation on Raphael's blog. The one I use, is roughly:

import inspect
import sys
import typing

_ExpType = typing.TypeVar('_ExpType')


def dbg(exp: _ExpType) -> _ExpType:
    for frame in inspect.stack():
        line = frame.code_context[0]

        if 'dbg' in line:
            start = line.find('(') + 1
            end = end if (end := line.rfind(')')) >= 0 else len(line) 

            print(f'[{frame.filename}:{frame.lineno}] {line[start:end]} = {exp!r}', 
                  file=sys.stderr)
            break

    return exp
Enter fullscreen mode Exit fullscreen mode

Whether in it's a *.py file or in a notebook, it works great. Exemplary output:

>>> a, b = 1, 2
... dbg(a + b)
[(...):2] a + b = 3
3
Enter fullscreen mode Exit fullscreen mode

Top comments (0)