Advanced Usage

This section covers more advanced icecream features for special use cases like project-wide availability and custom object formatting.

Global Availability with install()

To make ic() available in every file of your project without importing it everywhere, you can use install(). This function adds ic() to the global builtins, making it accessible just like print() or len().

Call install() once in your project's main entry point.

In your main file (e.g., main.py):

from icecream import install

# Make ic() available globally
install()

# Now import other modules
import my_module

my_module.do_stuff()

In another file (e.g., my_module.py):

def do_stuff():
    x = {'a': 1}
    ic(x) # No import needed!

To reverse this, you can call uninstall() to remove ic from the builtins.

from icecream import uninstall

# Remove ic() from builtins
uninstall()

Graceful Fallback in Production

While icecream is a development tool, you might forget to remove ic() calls before deploying to production where icecream may not be installed. To prevent crashes, you can use this snippet which provides a dummy ic function if the real one can't be imported.

try:
    from icecream import ic
except ImportError:  # Graceful fallback if IceCream isn't installed.
    ic = lambda *a: None if not a else (a[0] if len(a) == 1 else a)  # noqa

This ensures your application runs smoothly even if icecream is not in the production environment.

Customizing Argument Formatting

icecream uses a powerful functools.singledispatch function called argumentToString to convert arguments into strings for display. You can extend this function to provide custom formatting for your own classes or other types.

To do this, import argumentToString and use its register() method as a decorator.

Example: Custom Formatting for numpy arrays

Let's say you want to display a summary of a numpy array instead of its full contents.

from icecream import ic, argumentToString
import numpy as np

# Register a custom formatting function for numpy.ndarray
@argumentToString.register(np.ndarray)
def _(obj):
    return f"ndarray, shape={obj.shape}, dtype={obj.dtype}"

x = np.zeros((2, 3))
ic(x)

Output:

ic| x: ndarray, shape=(2, 3), dtype=float64

Managing Custom Formatters

You can also view all registered functions or unregister a specific one:

  • View registry: argumentToString.registry
  • Unregister: argumentToString.unregister(np.ndarray)
# View registered functions
print(argumentToString.registry)

# Unregister the custom formatter
argumentToString.unregister(np.ndarray)

ic(x) # Falls back to the default pprint format

Output after unregistering:

ic| x: array([[0., 0., 0.],
       [0., 0., 0.]])
This feature provides deep control over how your data is displayed during debugging. For more general output control, see the Configuration page.