DEV Community

qoqosz
qoqosz

Posted on

1 1

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

Quadratic AI

Quadratic AI – The Spreadsheet with AI, Code, and Connections

  • AI-Powered Insights: Ask questions in plain English and get instant visualizations
  • Multi-Language Support: Seamlessly switch between Python, SQL, and JavaScript in one workspace
  • Zero Setup Required: Connect to databases or drag-and-drop files straight from your browser
  • Live Collaboration: Work together in real-time, no matter where your team is located
  • Beyond Formulas: Tackle complex analysis that traditional spreadsheets can't handle

Get started for free.

Watch The Demo 📊✨

Top comments (0)

Image of Checkly

4 Playwright Locators Explained: Which One Should You Use?

- locator('.cta'): Fast but brittle
- getByText('Click me'): User-facing, but can miss broken accessibility
- getByRole('button', { name: 'Click me' }): Most robust, best for a11y
- getByTestId('cta-button'): Stable, but ignores UX

Watch video

👋 Kindness is contagious

DEV is better (more customized, reading settings like dark mode etc) when you're signed in!

Okay