Print and evaluate in python3

Viewed 86

Currently for my scientific experiments I use

dbg = print
# def dbg(*args): pass

So I have a lot of dbg(x, y, f(x)) in code, all of which I can "turn off" my commenting one line and uncommenting another.

However, the output looks brief, e.g. 0 15 32.
Is there a way to make it look like x = 0, y = 15, f(x) = 32?

I tried to write something using eval, but couldn't.

1 Answers

Try using the = operator on f-strings:

dbg(f"{x=}, {y=}, {f(x)=}")

This was introduced in Python3.8 f-strings support = for self-documenting expressions and debugging

Added an = specifier to f-strings. An f-string such as f'{expr=}' will expand to the text of the expression, an equal sign, then the representation of the evaluated expression. For example:

>>> user = 'eric_idle'
>>> member_since = date(1975, 7, 31)
>>> f'{user=} {member_since=}'
"user='eric_idle' member_since=datetime.date(1975, 7, 31)"
Related