print() method to print passed expression literally along with computed output for quick debugging
f-strings will support something like this in Python 3.8+.
From the docs:
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)"
The usual f-string format specifiers allow more control over how the result of the expression is displayed:
>>> delta = date.today() - member_since
>>> f'{user=!s} {delta.days=:,d}'
'user=eric_idle delta.days=16,075'
The = specifier will display the whole expression so that calculations can be shown:
>>> print(f'{theta=} {cos(radians(theta))=:.3f}')
theta=30 cos(radians(theta))=0.866
Generally I think if you find yourself using eval
there's probably a better way to do what you're trying to do, but:
for statement in ["42 + 42", "type(list)", "datetime.now()"]:
print("{} : {}".format(statement, eval(statement))
You could define a superprint
function and have it print then evaluate a string:
from datetime import datetime
def superprint(str):
print(str," : ",eval(str))
a = "42 + 42"
b = "type(list)"
c = "datetime.now()"
superprint(a)
superprint(b)
superprint(c)
42 + 42 : 84
type(list) : <class 'type'>
datetime.now() : 2019-08-15 14:44:43.072780
If you can live with tossing everything you want to print in quotation marks this could work for you.