Hi Pythonistas!
Today we are going to learn a new module called icecream. Icecream module is used to debug the code but it is better than the print statement. The feature of icecream are
- It prints both expressions/variable names and their values.
- It's 60% faster to type.
- Data structures are pretty printed.
- Output is syntax highlighted.
- It optionally includes program context: filename, line number, and parent function.
Let us dive into the code
Installation
pip install icecream
Code
from icecream import ic
x = 10
ic(x)
y = 20
ic(y, x+y)
ic(range(5))
ic({
"one": 1,
"two": 2,
"three": 3
})
ic(list(range(5)))
def square(i):
return i*i
a = ic(square(4))
Output
ic| x: 10
ic| y: 20, x+y: 30
ic| range(5): range(0, 5)
ic| {'one': 1, 'three': 3, 'two': 2}
ic| list(range(5)): [0, 1, 2, 3, 4]
ic| square(4): 16
Find the code block
def gfg(value):
ic()
if value == True:
ic()
return "GFG"
else:
ic()
return -1
ic(gfg(True))
Output
ic| icecreame_into.py:31 in gfg() at 08:48:32.289
ic| icecreame_into.py:33 in gfg() at 08:48:32.290
ic| gfg(True): 'GFG'
If we use empty ic function the we get the proper block of code executed
Enable and disable icecream
Ice Cream has a method to enable or disable its working. By default is is enabled mode but we can make it disable using this function.
ic.disable()
ic("hello disable")
ic(square(5))
ic.enable()
ic("hello enable")
ic(square(5))
Output
ic| 'hello enable'
ic| square(5): 25
We can see that the code after disabled is not printed in the console. But after enabling it is shown properly
I hope you have learned something from this post.Please share your valuable suggestions with afsal@parseltongue.co.in