### Installation Source: https://github.com/gruns/icecream/blob/master/README.md Instructions on how to install the IceCream library. ```APIDOC ## Installation ### Description Installs the IceCream library using pip. ### Method `pip install icecream` ### Endpoint N/A ### Parameters None ### Request Example ```bash $ pip install icecream ``` ### Response #### Success Response (200) Installation is successful. #### Response Example ``` Collecting icecream Downloading icecream-2.1.2-py2.py3-none-any.whl (11 kB) Installing collected packages: icecream Successfully installed icecream-2.1.2 ``` ``` -------------------------------- ### Install IceCream using pip Source: https://github.com/gruns/icecream/blob/master/README.md Instructions for installing the IceCream library using the pip package manager. ```bash pip install icecream ``` -------------------------------- ### Global IceCream Installation Source: https://github.com/gruns/icecream/blob/master/README.md Details the `install()` function, which makes `ic()` available globally as a built-in function across all modules without explicit imports in each file. It also mentions the corresponding `uninstall()` function. ```python # In A.py #!/usr/bin/env python3 # -*- coding: utf-8 -*- from icecream import install install() from B import foo foo() ``` ```python # In B.py # -*- coding: utf-8 -*- def foo(): x = 3 ic(x) ``` -------------------------------- ### Graceful IceCream Import Fallback Source: https://github.com/gruns/icecream/blob/master/README.md Provides a Python snippet for importing `ic` that includes a fallback mechanism. If the `icecream` library is not installed, `ic` is defined as a no-op function, preventing `ImportError` and allowing the code to run gracefully in environments where IceCream is not available. ```python 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 ``` -------------------------------- ### Register Custom Argument Serialization for NumPy Arrays Source: https://github.com/gruns/icecream/blob/master/README.md Extend IceCream's argument serialization to handle specific types like NumPy arrays using functools.singledispatch. This example registers a function to summarize ndarrays. ```python 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) # Output: ic| x: ndarray, shape=(1, 2), dtype=float64 # View registered functions print(argumentToString.registry) # Unregister a function and fallback to the default behavior argumentToString.unregister(np.ndarray) ic(x) # Output: ic| x: array([[0., 0.]]) ``` -------------------------------- ### Collapse Whitespace in Icecream Arguments Source: https://github.com/gruns/icecream/blob/master/changelog.txt This update modifies `ic()` to collapse excessive whitespace within arguments, normalizing the output for better consistency. For example, `ic([ a, b ])` is now rendered as `ic| [a, b]`. ```python ic([ a, b ]) ``` -------------------------------- ### Create Multiple IceCream Debugger Instances Source: https://context7.com/gruns/icecream/llms.txt Explains how to create independent `IceCreamDebugger` instances with distinct configurations, such as custom prefixes, context inclusion, or output functions. This allows for separating debug output by subsystem or log level, and directing output to files or stdout. ```python from icecream import IceCreamDebugger import sys # Create specialized debuggers db_debug = IceCreamDebugger(prefix='[DB] ', includeContext=True) api_debug = IceCreamDebugger(prefix='[API] ') perf_debug = IceCreamDebugger(prefix='[PERF] ') # Use different debuggers in different parts of code def database_query(sql): db_debug(sql) # [DB] db.py:15 in database_query()- sql: 'SELECT * FROM users' return [] def api_handler(request): api_debug(request) # [API] request: {'method': 'GET', 'path': '/users'} return {"status": "ok"} def measure_time(operation, duration): perf_debug(operation, duration) # [PERF] operation: 'query', duration: 0.042 # Debugger with custom output function def file_output(s): with open('debug.log', 'a') as f: f.write(s + '\n') file_debug = IceCreamDebugger(prefix='', outputFunction=file_output) file_debug("logged to file") # Writes to debug.log instead of stderr # Debugger with stdout instead of stderr stdout_debug = IceCreamDebugger() stdout_debug.use_stdout() stdout_debug("goes to stdout") ``` -------------------------------- ### Store Debug Snapshots with IceCream Source: https://context7.com/gruns/icecream/llms.txt Demonstrates how to use IceCream to log intermediate values during a loop. The `ic.format()` function is used to capture the state of variables at each iteration, and the collected logs are then printed. ```python from icecream import ic debug_log = [] for i in range(3): result = i ** 2 debug_log.append(ic.format(i, result)) print("\n".join(debug_log)) ``` -------------------------------- ### Logging Integration Source: https://github.com/gruns/icecream/blob/master/README.md How to integrate IceCream's output with Python's logging module. ```APIDOC ## `ic.format()` for Logging ### Description Integrates IceCream's debugging output with Python's `logging` module using `ic.format()`. ### Method `ic.format(argument)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **argument** (any) - The argument to be formatted by IceCream. ### Request Example ```python import logging from icecream import ic foo = 'bar' logging.debug(ic.format(foo)) ``` ### Response #### Success Response (200) Returns a formatted string suitable for logging. #### Response Example ``` 'ic| foo: 'bar'' ``` ``` -------------------------------- ### Using IceCream Return Values Source: https://github.com/gruns/icecream/blob/master/README.md Shows how `ic()` can be seamlessly integrated into existing code by returning its arguments. This allows `ic()` to be placed within assignments or function calls without altering the program's flow or breaking existing logic. ```python a = 6 def half(i): return i / 2 b = half(ic(a)) ic(b) ``` -------------------------------- ### Configure IceCream to Include Call Context Source: https://github.com/gruns/icecream/blob/master/README.md Enable the inclusion of the filename, line number, and parent function in ic() output. This is False by default. ```python from icecream import ic ic.configureOutput(includeContext=True) def foo(): i = 3 ic(i) foo() # Output: ic| example.py:12 in foo()- i: 3 ``` -------------------------------- ### Customize IceCream Output with ic.configureOutput() in Python Source: https://context7.com/gruns/icecream/llms.txt The `ic.configureOutput()` function allows customization of IceCream's debugging output. Options include custom string or callable prefixes, custom output functions (e.g., for logging), argument-to-string formatting, inclusion of execution context (filename, line number, function name), and line wrapping. ```python from icecream import ic import logging import time # Custom string prefix ic.configureOutput(prefix='DEBUG -> ') ic(42) # DEBUG -> 42 # Dynamic prefix with function def timestamp_prefix(): return f'[{time.strftime("%H:%M:%S")}] ' ic.configureOutput(prefix=timestamp_prefix) ic("hello") # [14:32:15] 'hello' # Custom output function (redirect to logging) logging.basicConfig(level=logging.DEBUG) def log_output(s): logging.debug(s) ic.configureOutput(prefix='ic| ', outputFunction=log_output) ic("test message") # DEBUG:root:ic| 'test message' # Include execution context ic.configureOutput(includeContext=True) def my_function(): value = 100 ic(value) # ic| script.py:28 in my_function()- value: 100 my_function() # Absolute paths in context ic.configureOutput(includeContext=True, contextAbsPath=True) ic("debug") # ic| /home/user/project/script.py:32 in - 'debug' # Custom line wrap width ic.configureOutput(lineWrapWidth=40) # Custom argument-to-string function def custom_formatter(obj): if isinstance(obj, dict): return f"" return repr(obj) ic.configureOutput(argToStringFunction=custom_formatter) ic({'a': 1, 'b': 2, 'c': 3}) # ic| {'a': 1, 'b': 2, 'c': 3}: # Reset to defaults ic.configureOutput( prefix='ic| ', outputFunction=None, # Falls back to stderr includeContext=False, contextAbsPath=False ) ``` -------------------------------- ### Custom Type Formatting with argumentToString Source: https://context7.com/gruns/icecream/llms.txt Illustrates how to register custom formatting functions for specific types using `argumentToString.register()` and `unregister()`. This leverages Python's singledispatch mechanism for pretty-printing custom classes or third-party objects like NumPy arrays. ```python from icecream import ic, argumentToString import numpy as np from dataclasses import dataclass # Register formatter for numpy arrays @argumentToString.register(np.ndarray) def format_numpy(arr): return f"ndarray(shape={arr.shape}, dtype={arr.dtype}, min={arr.min():.2f}, max={arr.max():.2f})" matrix = np.random.rand(3, 4) ic(matrix) # ic| matrix: ndarray(shape=(3, 4), dtype=float64, min=0.12, max=0.98) # Register formatter for custom class @dataclass class User: id: int name: str email: str @argumentToString.register(User) def format_user(user): return f"User<{user.id}: {user.name}>" user = User(id=42, name="Alice", email="alice@example.com") ic(user) # ic| user: User<42: Alice> # View all registered formatters print(argumentToString.registry) # mappingproxy({object: , # numpy.ndarray: , # User: }) # Unregister to restore default behavior argumentToString.unregister(np.ndarray) ic(matrix) # ic| matrix: array([[0.12, 0.45, ...], ...]) argumentToString.unregister(User) ic(user) # ic| user: User(id=42, name='Alice', email='alice@example.com') ``` -------------------------------- ### Inspect Execution Flow with IceCream Source: https://github.com/gruns/icecream/blob/master/README.md Illustrates using `ic()` without arguments to track program execution. When called with no arguments, `ic()` prints the current filename, line number, and parent function, helping to understand the order of execution and identify which code paths are being taken. ```python from icecream import ic def foo(): ic() first() if expression: ic() second() else: ic() third() ``` -------------------------------- ### Inspect Variables with IceCream Source: https://github.com/gruns/icecream/blob/master/README.md Demonstrates how to use `ic()` to inspect and print the values of variables and expressions. It shows how `ic()` automatically formats output to include the expression and its corresponding value, simplifying debugging compared to manual print statements. ```python from icecream import ic def foo(i): return i + 333 ic(foo(123)) ``` ```python d = {'key': {1: 'one'}} ic(d['key'][1]) class klass(): attr = 'yep' ic(klass.attr) ``` -------------------------------- ### Format Output to String with IceCream Source: https://github.com/gruns/icecream/blob/master/README.md Explains the `ic.format()` method, which is similar to `ic()` but returns the formatted output as a string instead of printing it to stderr. This is useful for logging or further processing of debugging information. ```python from icecream import ic s = 'sup' out = ic.format(s) print(out) ``` -------------------------------- ### Enable/Disable Debugging with IceCream Source: https://context7.com/gruns/icecream/llms.txt Demonstrates how to independently enable or disable debugging for different modules (e.g., database, API) using IceCream's disable() and enable() methods. This allows fine-grained control over debug output. ```python db_debug.disable() # Silence database debugging api_debug.enable() # Keep API debugging active db_debug("silent") # (no output) api_debug("visible") # [API] 'visible' ``` -------------------------------- ### Configuration API Source: https://github.com/gruns/icecream/blob/master/README.md Controls the output format and behavior of the ic() function. ```APIDOC ## `ic.configureOutput()` ### Description Controls `ic()`'s output formatting and behavior. ### Method `ic.configureOutput(prefix, outputFunction, argToStringFunction, includeContext, contextAbsPath)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **prefix** (string or function) - Optional - A custom output prefix. Defaults to `ic| `. - **outputFunction** (function) - Optional - A function called with `ic()`'s output string instead of writing to stderr. - **argToStringFunction** (function) - Optional - A function called with argument values to serialize them into displayable strings. Defaults to `pprint.pformat()`. - **includeContext** (boolean) - Optional - If True, includes filename, line number, and parent function in the output. Defaults to False. - **contextAbsPath** (boolean) - Optional - If True and `includeContext` is True, outputs absolute file paths. Defaults to False. ### Request Example ```python from icecream import ic # Example with string prefix ic.configureOutput(prefix='hello -> ') ic('world') # Example with function prefix def unixTimestamp(): return '%i |> ' % int(time.time()) ic.configureOutput(prefix=unixTimestamp) ic('world') # Example with custom output function import logging def warn(s): logging.warning("%s", s) ic.configureOutput(outputFunction=warn) ic('eep') # Example with custom argument to string function def toString(obj): if isinstance(obj, str): return '[!string %r with length %i!]' % (obj, len(obj)) return repr(obj) ic.configureOutput(argToStringFunction=toString) ic(7, 'hello') # Example with includeContext ic.configureOutput(includeContext=True) def foo(): i = 3 ic(i) foo() # Example with includeContext and contextAbsPath ic.configureOutput(includeContext=True, contextAbsPath=True) def foo(): ic(i) foo() ``` ### Response #### Success Response (200) This method does not return a value; it configures the `ic` object. #### Response Example None ``` -------------------------------- ### Configure IceCream to Use Absolute File Paths in Context Source: https://github.com/gruns/icecream/blob/master/README.md When includeContext is True, this option determines whether to use absolute file paths or just filenames. Setting contextAbsPath to True provides absolute paths, which can be useful for editor integration. Defaults to False. ```python from icecream import ic ic.configureOutput(includeContext=True, contextAbsPath=True) i = 3 def foo(): ic(i) foo() # Output: ic| /absolute/path/to/example.py:12 in foo()- i: 3 ic.configureOutput(includeContext=True, contextAbsPath=False) def foo(): ic(i) foo() # Output: ic| example.py:18 in foo()- i: 3 ``` -------------------------------- ### Format Output for Python Logging Source: https://github.com/gruns/icecream/blob/master/README.md Integrate IceCream's debugging output with Python's logging module using the ic.format() method. This allows for structured logging of debug information. ```python import logging from icecream import ic foo = 'bar' logging.debug(ic.format(foo)) ``` -------------------------------- ### Configure IceCream Argument Serialization Source: https://github.com/gruns/icecream/blob/master/README.md Define a custom function to serialize argument values for ic() output. This allows for custom handling of data types. Defaults to pprint.pformat(). ```python from icecream import ic def toString(obj): if isinstance(obj, str): return '[!string %r with length %i!]' % (obj, len(obj)) return repr(obj) ic.configureOutput(argToStringFunction=toString) ic(7, 'hello') # Output: ic| 7: 7, 'hello': [!string 'hello' with length 5!] ``` -------------------------------- ### Colorize Icecream Output with Pygments Source: https://github.com/gruns/icecream/blob/master/changelog.txt Introduces output colorization for `ic()` using the Pygments library, making the debug output more visually distinct and easier to parse. ```python # Assumes pygments is installed: pip install pygments from icecream import ic ic('Hello, World!') ``` -------------------------------- ### Enable/Disable IceCream Output Source: https://github.com/gruns/icecream/blob/master/README.md Demonstrates how to control the output of `ic()` using `ic.disable()` and `ic.enable()`. This feature allows temporarily turning off all IceCream debugging output without removing the `ic()` calls from the code, which is useful for production environments or specific debugging scenarios. ```python from icecream import ic ic(1) ic.disable() ic(2) ic.enable() ic(3) ``` -------------------------------- ### Configure IceCream Output Prefix Source: https://github.com/gruns/icecream/blob/master/README.md Customize the output prefix for ic() calls. The prefix can be a string or a function that returns a string. Defaults to 'ic| '. ```python from icecream import ic ic.configureOutput(prefix='hello -> ') ic('world') # Output: hello -> 'world' ``` ```python import time from icecream import ic def unixTimestamp(): return '%i |> ' % int(time.time()) ic.configureOutput(prefix=unixTimestamp) ic('world') # Output: 1519185860 |> 'world': 'world' ``` -------------------------------- ### Configure IceCream Output Function Source: https://github.com/gruns/icecream/blob/master/README.md Specify a custom function to handle ic() output. Instead of writing to stderr, the provided function will be called with the formatted output string. ```python import logging from icecream import ic def warn(s): logging.warning("%s", s) ic.configureOutput(outputFunction=warn) ic('eep') # Output: WARNING:root:ic| 'eep': 'eep' ``` -------------------------------- ### Parse and Print Tuple Arguments Correctly in Icecream Source: https://github.com/gruns/icecream/blob/master/changelog.txt Fixes an issue where `ic()` did not correctly parse and print tuple arguments. This ensures that tuples passed to `ic()` are displayed accurately in the output. ```python ic((a, b)) ``` -------------------------------- ### Graceful Error Handling for Source Code Access in Icecream Source: https://github.com/gruns/icecream/blob/master/changelog.txt Improves error handling for `ic()` invocations when source code is inaccessible (e.g., within `eval()`, `exec()`, or `python -i`). It now prints an error message instead of raising an exception. ```python # Example scenario where source code might be inaccessible try: exec('ic(1)') except Exception as e: print(f'An error occurred: {e}') ``` -------------------------------- ### Test Python Style with Pycodestyle Source: https://github.com/gruns/icecream/blob/master/changelog.txt Adds the capability to test Python code style using `pycodestyle` within the project's testing suite, ensuring adherence to PEP 8 guidelines. ```python # Example of running pycodestyle on a file import subprocess subprocess.run(['pycodestyle', 'your_script.py']) ``` -------------------------------- ### Support Multiline Container Arguments in Icecream Source: https://github.com/gruns/icecream/blob/master/changelog.txt This change allows `ic()` calls to correctly handle container arguments that span multiple lines, improving readability for complex data structures. ```python ic([ a, b ]) ``` -------------------------------- ### Inspect Variables and Expressions with ic() in Python Source: https://context7.com/gruns/icecream/llms.txt The primary function `ic()` from the IceCream library inspects and prints variable names/expressions alongside their values. It supports basic variables, complex expressions, data structures, multiple arguments, and execution tracing. It returns arguments unchanged, allowing seamless integration. ```python from icecream import ic # Basic variable inspection name = "Alice" age = 30 ic(name) # ic| name: 'Alice' ic(age) # ic| age: 30 # Expression inspection def calculate(x, y): return x * y + 10 ic(calculate(5, 3)) # ic| calculate(5, 3): 25 # Data structure pretty-printing data = {'users': [{'name': 'Alice', 'scores': [95, 87, 92]}, {'name': 'Bob', 'scores': [88, 91, 85]}]} ic(data) # ic| data: {'users': [{'name': 'Alice', 'scores': [95, 87, 92]}, # {'name': 'Bob', 'scores': [88, 91, 85]}]} # Multiple arguments x, y, z = 1, 2, 3 ic(x, y, z) # ic| x: 1, y: 2, z: 3 # Passthrough - ic() returns its argument result = ic(calculate(10, 5)) # ic| calculate(10, 5): 60 print(result) # 60 # Execution tracing (no arguments) def process_order(order_id): ic() # ic| script.py:25 in process_order() if order_id > 100: ic() # ic| script.py:27 in process_order() return "premium" else: ic() # ic| script.py:30 in process_order() return "standard" ``` -------------------------------- ### Print Values Directly in Icecream Source: https://github.com/gruns/icecream/blob/master/changelog.txt Changes `ic()` behavior to print standalone values more concisely. For instance, `ic(3)` now outputs `ic| 3` instead of the redundant `ic| 3: 3`. ```python ic(3) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.