Stop Using Print To Debug in Python. Use Icecream Instead - by Khuyen Tran - Jan, 2021 - Towards Data Science
Stop Using Print To Debug in Python. Use Icecream Instead - by Khuyen Tran - Jan, 2021 - Towards Data Science
Use
Icecream Instead
Are you Using Print or Log to Debug your Code? Use Icecream instead.
Khuyen Tran
Motivation
If you are using print to debug your code, you might find it confusing to look at many
lines of output on your terminal and then try to figure out which code each output
belongs to.
1 num1 = 30
2 num2 = 40
3
4 print(num1)
5 print(num2)
30
40
Which one of these outputs is num1 ? Which one of these outputs is num2 ? Two outputs
might not be so bad to figure out, but what if there are more than 5 different outputs? To
try to find the source code that is responsible for the output can be time-consuming.
You might try to add text to the print statement to make it easier to figure out:
1 num1 = 30
2 num2 = 40
3
4 print('num1', num1)
5 print('num2', num2)
num1 30
num2 40
The output is easier to read, but again, it is time-consuming to write out the text. Is there
a way to print the code that is responsible for the output without additional text like
below?
1 num1 = 30
2 num2 = 40
3
4 ic(num1)
5 ic(num2)
ic| num1: 30
ic| num2: 40
By using ic , we do not only see the output but also see the function and its arguments!
How convenient! The color in your terminal will also be as colorful as the outputs shown
above.
Inspect Execution
To locate where the code was executed, you might do something like what is shown
below to find which statement was executed
1 def hello(user:bool):
2 if user:
3 print("I'm user")
4 else:
5 print("I'm not user")
6
7 hello(user=True)
I'm user
Icecream makes it easier for you to do something like the above by simply running ic()
Custom Prefix
If you would like to insert a custom prefix such as the time the code was executed to
your print statement, icecream also allows you to do so.
Now the time that the code is executed is automatically shown in the output! How cool
is that?
Now you know that the first output was executed by the function plus_five from the
file icecream_example.py at line 7.
Conclusion
Congratulations! You have just learned how to make print debugging more readable
using icecream. Icecream has been a great debugging tool for me, and I hope you will
find it useful as well.