Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

print() method to print passed expression literally along with computed output for quick debugging

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!

like image 829
Sagar Gupta Avatar asked Aug 15 '19 17:08

Sagar Gupta


People also ask

How do you print parentheses in Python?

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.

Is print a function in Python?

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).


2 Answers

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 
like image 55
snakecharmerb Avatar answered Sep 20 '22 19:09

snakecharmerb


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)) 
like image 23
it's-yer-boy-chet Avatar answered Sep 22 '22 19:09

it's-yer-boy-chet