or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

index.md
tile.json

tessl/pypi-icecream

Never use print() to debug again; inspect variables, expressions, and program execution with a single, simple function call.

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
pypipkg:pypi/icecream@2.1.x

To install, run

npx @tessl/cli install tessl/pypi-icecream@2.1.0

index.mddocs/

IceCream

Never use print() to debug again; inspect variables, expressions, and program execution with a single, simple function call. IceCream (ic) makes print debugging 60% faster to type, automatically displays variable names and values, and provides syntax highlighting and contextual information.

Package Information

  • Package Name: icecream
  • Package Type: pypi
  • Language: Python
  • Installation: pip install icecream

Core Imports

from icecream import ic

Additional imports:

from icecream import (
    ic,                    # Main debug function
    install, uninstall,    # Global installation
    argumentToString,      # Custom type formatting
    stderrPrint,          # Utility function for stderr output
    IceCreamDebugger      # Main debugger class
)

For global installation (optional):

from icecream import install
install()
# Now ic() is available globally without import

Basic Usage

from icecream import ic

# Simple variable inspection
x = 42
ic(x)  # Output: ic| x: 42

# Expression inspection
def calculate(a, b):
    return a * b + 10

result = ic(calculate(5, 3))  # Output: ic| calculate(5, 3): 25
print(result)  # 25 (ic returns the value)

# Execution tracking (no arguments)
def process_data():
    ic()  # Output: ic| example.py:12 in process_data()
    # ... processing code
    ic()  # Output: ic| example.py:15 in process_data()

# Multiple arguments
name = "Alice"
age = 30
ic(name, age)  # Output: ic| name: 'Alice', age: 30

# Complex data structures
data = {'users': [1, 2, 3], 'status': 'active'}
ic(data)
# Output: ic| data: {'users': [1, 2, 3], 'status': 'active'}

Capabilities

Core Debugging Function

The main debugging function that automatically prints variable names and values with syntax highlighting.

def ic(*args):
    """
    Debug function that prints variable names and values.
    
    Parameters:
    - *args: Any number of variables, expressions, or values to inspect
    
    Returns:
    - None if no arguments provided
    - Single value if one argument provided  
    - Tuple of values if multiple arguments provided
    
    Examples:
    - ic() prints execution context (filename, line, function)
    - ic(x) prints "ic| x: <value>" and returns x
    - ic(x, y) prints "ic| x: <value>, y: <value>" and returns (x, y)
    """

Output Formatting

Get formatted debug output as a string instead of printing to stderr.

def format(*args) -> str:
    """
    Returns formatted debug output as string.
    
    Parameters:
    - *args: Variables or expressions to format
    
    Returns:
    - str: Formatted debug output string
    """

Output Control

Enable and disable debug output while preserving return values.

def enable() -> None:
    """Enable debug output (enabled by default)."""

def disable() -> None:
    """Disable debug output while maintaining return values."""

Output Configuration

Customize output formatting, destination, and behavior.

def configureOutput(
    prefix=_absent,
    outputFunction=_absent, 
    argToStringFunction=_absent,
    includeContext=_absent,
    contextAbsPath=_absent,
    lineWrapWidth=_absent
) -> None:
    """
    Configure debug output formatting and behavior.
    
    Parameters:
    - prefix (str or callable, optional): Custom output prefix (default: 'ic| ')
    - outputFunction (callable, optional): Custom output function (default: colorized stderr print)
    - argToStringFunction (callable, optional): Custom string conversion function (default: argumentToString)
    - includeContext (bool, optional): Include filename/line/function info (default: False)
    - contextAbsPath (bool, optional): Use absolute paths in context (default: False)  
    - lineWrapWidth (int, optional): Max line width before wrapping (default: 70)
    
    Raises:
    - TypeError: If no parameters are provided
    
    Note: All parameters are optional. Only provided parameters will be updated.
    """

Global Installation

Install ic() function globally as a builtin for use without imports.

def install(ic='ic') -> None:
    """
    Install ic() globally as builtin function.
    
    Parameters:
    - ic (str): Name to install as (default: 'ic')
    """

def uninstall(ic='ic') -> None:
    """
    Remove globally installed ic() function.
    
    Parameters:
    - ic (str): Name to remove (default: 'ic')
    """

Custom Type Formatting

Register custom string conversion functions for specific types using single dispatch.

@functools.singledispatch
def argumentToString(obj) -> str:
    """
    Convert object to string representation for debug output.
    Uses pprint.pformat() by default with fallback to repr().
    
    Parameters:
    - obj: Object to convert to string
    
    Returns:
    - str: String representation of the object
    
    Attributes:
    - registry: mappingproxy showing registered type formatters  
    - register: Method to register formatters for specific types
    - unregister: Method to remove registered formatters (added dynamically)
    """

@argumentToString.register(YourCustomType)
def _(obj: YourCustomType) -> str:
    """Register custom formatter for YourCustomType."""
    return f"CustomType({obj})"

# Access the registry property
argumentToString.registry  # mappingproxy of registered formatters

# Unregister a type (method added dynamically by custom singledispatch)
argumentToString.unregister(YourCustomType)  # Remove custom formatter

Utility Functions

Lower-level functions available for advanced usage.

def stderrPrint(*args) -> None:
    """
    Print arguments to stderr.
    
    Parameters:
    - *args: Arguments to print to stderr
    """

def colorize(s: str) -> str:
    """
    Apply syntax highlighting to string using Pygments.
    
    Parameters:
    - s (str): String to colorize
    
    Returns:
    - str: Colorized string with ANSI escape codes
    """

Constants

Configuration constants available for reference.

DEFAULT_PREFIX: str = 'ic| '                      # Default output prefix
DEFAULT_LINE_WRAP_WIDTH: int = 70                 # Default line wrap width
DEFAULT_CONTEXT_DELIMITER: str = '- '             # Context delimiter
DEFAULT_OUTPUT_FUNCTION: callable                 # Default colorized stderr print
DEFAULT_ARG_TO_STRING_FUNCTION: callable          # Default argumentToString function
NO_SOURCE_AVAILABLE_WARNING_MESSAGE: str          # Warning when source unavailable

Advanced Usage Examples

Custom Prefix and Context

from icecream import ic

# Custom prefix with timestamp
import time
def timestamp():
    return f'{int(time.time())} |> '

ic.configureOutput(prefix=timestamp, includeContext=True)
ic('debugging')
# Output: 1519185860 |> example.py:8 in <module>- 'debugging': 'debugging'

Custom Output Function

import logging
from icecream import ic

# Log debug output instead of printing
def log_debug(s):
    logging.warning(s)

ic.configureOutput(outputFunction=log_debug)
ic('logged message')
# Sends to Python logging system instead of stderr

Custom Type Formatting

from icecream import ic, argumentToString
import numpy as np

# Register numpy array formatter
@argumentToString.register(np.ndarray)
def _(obj):
    return f"ndarray(shape={obj.shape}, dtype={obj.dtype})"

x = np.zeros((10, 5))
ic(x)  # Output: ic| x: ndarray(shape=(10, 5), dtype=float64)

Graceful Fallback

# Fallback for production environments
try:
    from icecream import ic
except ImportError:
    ic = lambda *a: None if not a else (a[0] if len(a) == 1 else a)

Types

class IceCreamDebugger:
    """
    Main debugger class. The global 'ic' instance is created from this class.
    
    Attributes:
    - enabled (bool): Controls whether output is printed (default: True)
    - prefix (str | callable): Output prefix (default: 'ic| ')
    - includeContext (bool): Include filename/line/function info (default: False)
    - outputFunction (callable): Function to handle output (default: colorized stderr)
    - argToStringFunction (callable): Function to convert args to strings (default: argumentToString)
    - contextAbsPath (bool): Use absolute paths in context (default: False)
    - lineWrapWidth (int): Max line width before wrapping (default: 70)
    - contextDelimiter (str): Delimiter between context and arguments (default: '- ')
    - _pairDelimiter (str): Delimiter between argument pairs (default: ', ')
    """
    
    def __init__(
        self,
        prefix: str | callable = DEFAULT_PREFIX,
        outputFunction: callable = DEFAULT_OUTPUT_FUNCTION,
        argToStringFunction: callable = argumentToString,
        includeContext: bool = False,
        contextAbsPath: bool = False
    ): ...
    
    def __call__(self, *args):
        """
        Main debug function. Prints variables and returns them.
        
        Parameters:
        - *args: Variables or expressions to debug
        
        Returns:
        - None if no arguments
        - Single value if one argument
        - Tuple if multiple arguments
        """
        
    def format(self, *args) -> str:
        """Return formatted debug output as string instead of printing."""
        
    def enable(self) -> None:
        """Enable debug output."""
        
    def disable(self) -> None:
        """Disable debug output while preserving return values."""
        
    def configureOutput(
        self,
        prefix=_absent,
        outputFunction=_absent,
        argToStringFunction=_absent,
        includeContext=_absent,
        contextAbsPath=_absent,
        lineWrapWidth=_absent
    ) -> None:
        """Configure output settings. See configureOutput() function for details."""

Error Handling

IceCream handles various edge cases gracefully:

  • Missing source code: Issues RuntimeWarning and shows values only when source code cannot be accessed (REPL sessions, frozen applications like PyInstaller, or when source changes during execution)
  • Complex objects: Falls back to repr() if pprint.pformat() fails due to comparison issues
  • Large outputs: Automatically wraps long lines based on lineWrapWidth setting
  • Import errors: Use graceful fallback pattern for production environments
  • Configuration errors: Raises TypeError if configureOutput() called with no parameters

Warning Messages

When IceCream cannot access source code, it issues this warning:

NO_SOURCE_AVAILABLE_WARNING_MESSAGE: str = (
    'Failed to access the underlying source code for analysis. Was ic() '
    'invoked in a REPL (e.g. from the command line), a frozen application '
    '(e.g. packaged with PyInstaller), or did the underlying source code '
    'change during execution?'
)

The warning is issued as a RuntimeWarning with stacklevel=4 to point to the actual ic() call location.

Version Information

Package metadata constants available for import:

__version__: str      # Package version (e.g., '2.1.7')
__title__: str        # Package name ('icecream')
__author__: str       # Author name ('Ansgar Grunseid') 
__license__: str      # License type ('MIT')
__contact__: str      # Author email ('grunseid@gmail.com')
__url__: str          # Project URL ('https://github.com/gruns/icecream')
__description__: str  # Package description
from icecream import __version__, __author__
print(f"IceCream v{__version__} by {__author__}")

Dependencies

  • colorama (>=0.3.9): Cross-platform colored terminal text
  • pygments (>=2.2.0): Syntax highlighting
  • executing (>=2.1.0): AST analysis for variable name detection
  • asttokens (>=2.0.1): AST token mapping for source code analysis

Python Compatibility

  • Python 3.8+
  • PyPy3
  • Cross-platform support (Windows, macOS, Linux)