IceCream (ic) Python Debugging Tool

repository·master·Indexed 26 days ago

https://github.com/gruns/icecream

A Python debugging tool that improves upon the standard print() function by automatically inspecting variables, expressions, and execution context with pretty-printed and syntax-highlighted output. Features include transparent return values, global availability via install(), output configuration through ic.configureOutput(), and custom string serialization for specific types.

Tokens
1.1K
Snippets
7
Records
10
Agent score
45%

What's inside IceCream

  1. Graceful fallback for ic() in production

    master

    If you want to use ic() in your code but don't want to require the icecream package in production environments, use this fallback snippet:

    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)
  2. Configure ic() output settings

    master

    Use ic.configureOutput() to customize how debug information is displayed.

    Available parameters:

    • prefix: A string or function to set a custom output prefix (default: 'ic| ').
    • outputFunction: A function called with the formatted string instead of writing to stderr.
    • argToStringFunction: A function used to serialize arguments to strings (default: icecream.argumentToString).
    • includeContext: Boolean to include filename, line number, and parent function (default: False).
    • contextAbsPath: Boolean to use absolute filepaths when includeContext is True (default: False).
  3. Use ic() as a transparent return value

    master

    ic() returns its arguments, allowing you to wrap existing expressions or function calls without breaking the code logic.

    a = 6
    def half(i):
        return i / 2
    
    b = half(ic(a))
    # Prints: ic| a: 6
    # b is now 3.0
  4. Make ic() available globally with install()

    master
    To avoid importing ic in every file, call install() in your application's entry point. This adds ic() to the Python builtins module, making it available in all imported modules.
  5. Register custom string serialization for types

    master

    The default argToStringFunction (which is icecream.argumentToString) allows you to register custom serialization logic for specific classes using register() and unregister(). This is useful for handling complex types like NumPy arrays.

    from icecream import ic, argumentToString
    import numpy as np
    
    @argumentToString.register(np.ndarray)
    def _(obj):
        return f"ndarray, shape={obj.shape}, dtype={obj.dtype}"
    
    x = np.zeros((1, 2))
    ic(x)
    # ic| x: ndarray, shape=(1, 2), dtype=float64
    
    argumentToString.unregister(np.ndarray)
    ic(x)
    # ic| x: array([[0., 0.]])
  6. Inspect execution flow with ic()

    master

    Call ic() without any arguments to inspect the execution context. It will print the calling filename, line number, and the parent function name.

    from icecream import ic
    
    def foo():
        ic()
        # Prints: ic| example.py:4 in foo()
    
    foo()
  7. Inspect variables and expressions with ic()

    master

    Use ic() to print both the expression/variable name and its value. This is a more informative alternative to print() as it automatically formats data structures and provides syntax highlighting.

    from icecream import ic
    
    def foo(i):
        return i + 333
    
    ic(foo(123))
    # Prints: ic| foo(123): 456
    
    d = {'key': {1: 'one'}}
    ic(d['key'][1])
    # Prints: ic| d['key'][1]: 'one'
  8. Format ic() output as a string with ic.format()

    master

    If you need the formatted debug string instead of printing it to stderr, use ic.format(*args). This is useful for integrating IceCream with logging modules.

    from icecream import ic
    import logging
    
    s = 'sup'
    out = ic.format(s)
    print(out)
    # Prints: ic| s: 'sup'
    
    # Integration with logging
    logging.debug(ic.format(s))