1 min read

Python Icecream Module

icecream is a library that makes debugging with print statements sweeter. It prints both the expression/variable name and its value, which is often what you want when debugging.

Installation

pip install icecream

Basic Usage

Import ic from icecream. It works like print, but better.

from icecream import ic

def foo(i):
    return i + 333

ic(foo(123))
# Output: ic| foo(123): 456

Inspecting Variables

It prints the variable name and value.

d = {'a': 1, 'b': 2}
ic(d['a'])
# Output: ic| d['a']: 1

Execution Flow

If you call ic() without arguments, it prints the filename, line number, and parent function. This is great for tracing execution flow.

def my_function():
    ic()

my_function()
# Output: ic| script.py:12 in my_function() at 14:30:00.123

Configuration

You can configure the output prefix and whether it includes context (filename, line number).

ic.configureOutput(prefix='Debug | ', includeContext=True)
ic('test')
# Output: Debug | script.py:20 in <module>- test

Disabling

You can disable icecream in production without removing the import statements.

ic.disable()
ic(1) # No output
ic.enable()

programming/python/python