I wish to be able to perform python debugging using print() or similar method where it prints the passed expression in addition to the usual output.
For instance, for the following code:
print(42 + 42) print(type(list)) print(datetime.now())
Current Output:
84 <class 'type'> 2019-08-15 22:43:57.805861
Expected Output:
42 + 42 : 84 type(list) : <class 'type'> datetime.now() : 2019-08-15 22:43:57.805861
Currently, the same can be achieved by manually adding the expression string, (not so elegant imho and violates DRY principle).
print("42 + 42 : ", 42 + 42) print("type(list) : ", type(list)) print("datetime.now() : ", datetime.now())
I've tried to override builtin print, but without success:
import builtins def print(*args, **kwargs): return builtins.print(*args, **kwargs) # passed expression isn't available here as string!
Is there a way to achieve this? Thanks!
The Python “SyntaxError: Missing parentheses in call to 'print'” error is raised when you try to print a value to the console without enclosing that value in parenthesis. To solve this error, add parentheses around any statements you want to print to the console. This is because, in Python 3, print is not a statement.
Print Function The Python print() function takes in any number of parameters, and prints them out on one line of text. The items are each converted to text form, separated by spaces, and there is a single '\n' at the end (the "newline" char).
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))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With