Usage Guide

This guide provides an in-depth look at the core features of icecream.

Inspecting Variables and Expressions

The most common use for ic() is to inspect the value of a variable or the result of an expression. ic() intelligently prints both the code context and the value.

Simple Variables

from icecream import ic

my_string = "Hello, World!"
my_number = 42
my_list = [1, 2, 3]

ic(my_string)
ic(my_number)
ic(my_list)

Output:

ic| my_string: 'Hello, World!'
ic| my_number: 42
ic| my_list: [1, 2, 3]

Complex Expressions

ic() can also handle more complex expressions, including dictionary access, object attributes, and function calls.

from icecream import ic

def add(a, b):
    return a + b

d = {'key': {1: 'one'}}
ic(d['key'][1])

class MyClass:
    attr = 'yep'
ic(MyClass.attr)

ic(add(10, 5))

Output:

ic| d['key'][1]: 'one'
ic| MyClass.attr: 'yep'
ic| add(10, 5): 15

Inspecting Execution Flow

When called without any arguments, ic() prints the file, line number, and parent function of the call. This is a powerful tool for tracing your program's execution path without manual logging.

from icecream import ic

def complex_logic(user_is_admin):
    ic()
    if user_is_admin:
        ic()
        # Admin-specific logic
    else:
        ic()
        # Regular user logic

complex_logic(False)

Output:

ic| your_script.py:4 in complex_logic()
ic| your_script.py:9 in complex_logic()

Return Value Passthrough

ic() is designed to be non-intrusive. It returns the argument(s) passed to it, so you can insert it into your existing code without needing to refactor.

  • ic() with no arguments returns None.
  • ic(arg) returns arg.
  • ic(arg1, arg2, ...) returns a tuple (arg1, arg2, ...).

This allows you to wrap functions or expressions seamlessly:

from icecream import ic

def half(i):
    return i / 2

value = 20
result = half(ic(value))

ic(result)

Output:

ic| value: 20
ic| result: 10.0

Disabling and Re-enabling Output

You can globally disable and re-enable icecream's output. This is useful for turning off debugging messages without removing the ic() calls from your code.

  • ic.disable(): Disables all output from ic().
  • ic.enable(): Re-enables output.

Even when disabled, ic() will still return its arguments, so your code's logic remains unaffected.

from icecream import ic

ic(1)  # Prints output

ic.disable()
ic(2)  # Does not print

ic.enable()
ic(3)  # Prints output again

Output:

ic| 1: 1
ic| 3: 3

Formatting Output as a String

If you want to capture icecream's formatted output as a string instead of printing it to stderr, use ic.format().

This is particularly useful for integrating icecream's detailed output with a standard logging library.

import logging
from icecream import ic

logging.basicConfig(level=logging.DEBUG)

foo = 'bar'
logging.debug(ic.format(foo))

Output:

DEBUG:root:ic| foo: 'bar'

For more advanced customization, see the Configuration and Advanced Usage pages.