We’ve all been there - staring at lines of Python code, trying to figure out why our script isn’t behaving as expected. Debugging is a crucial skill for any programmer, but printing variables (e.g. print()) all over the place can quickly become messy and cumbersome.
Enter IceCream - a sweet little debugging library that makes logging variables and expressions a piece of cake.
IceCream is inspired by the popular debugging approach in JavaScript where you can sprinkle console.log() statements throughout your code. Similarly, with IceCream you simply import the library and use the ic() function to log variables, data structures, and even complex objects with a single line.
Let’s start
Installing IceCream is easy with pip:
pip install icecream
In your Python script, just import the library:
from icecream import ic
Basic usage
Let’s look at a simple example of using ic() for debugging:
from icecream import ic
x = 42
y = "hello"
ic(x)
ic(y)
ic(x + 10)
Output:
ic| x: 42
ic| y: 'hello'
ic| x + 10: 52
The ic() function automatically prints out the variable name and its value, making it easy to inspect variables at different points in your code. This beats having to write print("x =", x) all over the place.
Advanced features
IceCream is more than just basic logging. It has some neat tricks up its sleeve:
- Object inspection -
ic()pretty-prints objects, data structures like dictionaries and lists, and even complex objects from libraries like NumPy and Pandas. - Elegance - no need to delete or comment out
ic()calls when you’re done debugging. IceCream automatically disables itself unless theIC_DISABLE_STDOUT=Falseenvironment variable is set. - Context - get full context with file name, line number, and even the code being executed.
- Formatting - customize how objects are displayed by providing a
caller_fmtstring. - Notebook cells - IceCream works beautifully with Jupyter Notebooks too.
Here’s an example of inspecting a dictionary:
from icecream import ic
user = {
"name": "Alice",
"age": 30,
"roles": ["admin", "editor"],
}
ic(user)
Output:
ic| user: {'name': 'Alice', 'age': 30, 'roles': ['admin', 'editor']}
ic() is amazing, right?
So give IceCream a try on your next Python project. It’s an incredibly useful tool that can make debugging feel like a walk in the park, or at least slightly sweeter. For more information and examples, check out the official IceCream documentation.