Wednesday, 21 August 2019

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!



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

No comments:

Post a Comment