Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Print and evaluate in python3

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.

like image 442
bohdan_trotsenko Avatar asked Dec 10 '22 23:12

bohdan_trotsenko


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)"
like image 90
Niel Godfrey Ponciano Avatar answered Dec 31 '22 16:12

Niel Godfrey Ponciano