gruns / icecream
- пятница, 16 февраля 2018 г. в 03:16:14
Sweet and Creamy Print Debugging
Do you ever use print()
statements to debug your code? Of course you
do. IceCream, or ic
for short, makes print()
debugging a little sweeter.
IceCream is well tested, permissively licensed, and supports Python 2, Python 3, PyPy2, and PyPy3.
Have you ever printed variables or expressions to debug your program? If you've ever typed something like
print(foo('123'))
or the more thorough
print("foo('123')", foo('123'))
then ic()
is here to help. With arguments, ic()
inspects itself and prints
both its arguments and its argument's values.
from icecream import ic
def foo(s):
return s[::-1]
ic(foo('123'))
Prints
ic| foo('123'): 321
Similarly,
d = {'d': {1: 'one'}}
ic(d['d'][1])
class klass():
attr = 'yep'
ic(klass.attr)
prints
ic| d['d'][1]: 'one'
ic| klass.attr: 'yep'
Just give ic()
a variable or expression and you're done. Easy.
Do you ever add print statments to determine which parts of your program are executed, and in which order they're executed? For example, if you've ever added prints statements to debug something like
def foo():
print(0)
first()
if expression:
print(1)
second()
else:
print(2)
third()
then ic()
helps here, too. Without arguments, ic()
inspects itself and
prints the calling filename and line number.
from icecream import ic
def foo():
ic()
first()
if expression:
ic()
second()
else:
ic()
third()
Prints
ic| example.py:4
ic| example.py:11
Just call ic()
and you're done. Simple.
Installing IceCream with pip is easy.
$ pip install icecream
IceCream is currently just for Python, but IceCream should be enjoyed with every language.
If you'd like a similar ic()
method in your favorite language, please open a
pull request! IceCream's goal is to sweeten print debugging with a handy-dandy
ic()
function in every language.