icecream README

The project's README from github.com/gruns/icecream. As one markdown file: README.md.

IceCream

IceCream — Never use print() to debug again

Do you ever use print() or log() to debug your code? Of course you do. IceCream, or ic for short, makes print debugging a little sweeter.

ic() is like print(), but better:

  1. It prints both variables and expressions along with their values.
  2. It's 60% faster to type.
  3. Data structures are formatted and pretty printed.
  4. Output is syntax highlighted.
  5. It optionally includes program context: filename, line number, and parent function.

IceCream is well tested, permissively licensed, and supports Python 3 and PyPy3.

IceCream is maintained by Jakeroid (Ivan Karabadzhak), with support from the confidential computing folks at 🌖 Lunal.

Inspect Variables

Have you ever printed variables or expressions to debug your program? If you've ever typed something like

print(foo('123'))

or the more thorough

print("foo('123')", foo('123'))

then ic() will put a smile on your face. With arguments, ic() inspects itself and prints both its own arguments and the values of those arguments.

from icecream import ic

def foo(i):
    return i + 333

ic(foo(123))

Prints

ic| foo(123): 456

Similarly,

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

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

Prints

ic| d['key'][1]: 'one'
ic| klass.attr: 'yep'

Just give ic() a variable or expression and you're done. Easy.

Inspect Execution

Have you ever used print() to determine which parts of your program are executed, and in which order they're executed? For example, if you've ever added print statements to debug code like

def foo():
    print(0)
    first()

    if expression:
        print(1)
        second()
    else:
        print(2)
        third()

then ic() helps here, too. Without arguments, ic() inspects itself and prints the calling filename, line number, and parent function.

from icecream import ic

def foo():
    ic()
    first()

    if expression:
        ic()
        second()
    else:
        ic()
        third()

Prints

ic| example.py:4 in foo()
ic| example.py:11 in foo()

Just call ic() and you're done. Simple.

Return Value

ic() returns its argument(s), so ic() can easily be inserted into pre-existing code.

>>> a = 6
>>> def half(i):
>>>     return i / 2
>>> b = half(ic(a))
ic| a: 6
>>> ic(b)
ic| b: 3

Miscellaneous

ic.format(*args) is like ic() but the output is returned as a string instead of written to stderr.

>>> from icecream import ic
>>> s = 'sup'
>>> out = ic.format(s)
>>> print(out)
ic| s: 'sup'

Additionally, ic()'s output can be entirely disabled, and later re-enabled, with ic.disable() and ic.enable() respectively.

from icecream import ic

ic(1)

ic.disable()
ic(2)

ic.enable()
ic(3)

Prints

ic| 1: 1
ic| 3: 3

ic() continues to return its arguments when disabled, of course; no existing code with ic() breaks.

Import Tricks

To make ic() available in every file without needing to be imported in every file, you can install() it. For example, in a root A.py:

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

from icecream import install
install()

from B import foo
foo()

and then in B.py, which is imported by A.py, just call ic():

# -*- coding: utf-8 -*-

def foo():
    x = 3
    ic(x)

install() adds ic() to the builtins module, which is shared amongst all files imported by the interpreter. Similarly, ic() can later be uninstall()ed, too.

ic() can also be imported in a manner that fails gracefully if IceCream isn't installed, like in production environments (i.e. not development). To that end, this fallback import snippet may prove useful:

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

Configuration

ic.configureOutput(prefix, outputFunction, argToStringFunction, includeContext, contextAbsPath) controls ic()'s output.

prefix, if provided, adopts a custom output prefix. prefix can be a string, like

>>> from icecream import ic
>>> ic.configureOutput(prefix='hello -> ')
>>> ic('world')
hello -> 'world'

or a function.

>>> import time
>>> from icecream import ic
>>>  
>>> def unixTimestamp():
>>>     return '%i |> ' % int(time.time())
>>>
>>> ic.configureOutput(prefix=unixTimestamp)
>>> ic('world')
1519185860 |> 'world': 'world'

prefix's default value is ic| .

outputFunction, if provided, is called once for every ic() call with ic()'s output, as a string, instead of that string being written to stderr (the default).

>>> import logging
>>> from icecream import ic
>>>
>>> def warn(s):
>>>     logging.warning("%s", s)
>>>
>>> ic.configureOutput(outputFunction=warn)
>>> ic('eep')
WARNING:root:ic| 'eep': 'eep'

argToStringFunction, if provided, is called with argument values to be serialized to displayable strings. The default is PrettyPrint's pprint.pformat(), but this can be changed to, for example, handle non-standard datatypes in a custom fashion.

>>> 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')
ic| 7: 7, 'hello': [!string 'hello' with length 5!]

The default argToStringFunction is icecream.argumentToString, and has methods to register and unregister functions to be dispatched for specific classes using functools.singledispatch. It also has a registry property to view registered functions.

>>> from icecream import ic, argumentToString
>>> import numpy as np
>>>
>>> # Register a function to summarize numpy array
>>> @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
>>>
>>> # View registered functions
>>> argumentToString.registry
mappingproxy({object: <function icecream.icecream.argumentToString(obj)>,
              numpy.ndarray: <function __main__._(obj)>})
>>>
>>> # Unregister a function and fallback to the default behavior
>>> argumentToString.unregister(np.ndarray)
>>> ic(x)
ic| x: array([[0., 0.]])

includeContext, if provided and True, adds the ic() call's filename, line number, and parent function to ic()'s output.

>>> from icecream import ic
>>> ic.configureOutput(includeContext=True)
>>>
>>> def foo():
>>>   i = 3
>>>   ic(i)
>>> foo()
ic| example.py:12 in foo()- i: 3

includeContext is False by default.

contextAbsPath, if provided and True, outputs absolute filepaths, like /path/to/foo.py, over just filenames, like foo.py, when ic() is called with includeContext == True. This is useful when debugging multiple files that share the same filename(s). Moreover, some editors, like VSCode, turn absolute filepaths into clickable links that open the file where ic() was called.

>>> from icecream import ic
>>> ic.configureOutput(includeContext=True, contextAbsPath=True)
>>>
>>> i = 3
>>>
>>> def foo():
>>>   ic(i)
>>> foo()
ic| /absolute/path/to/example.py:12 in foo()- i: 3
>>>
>>> ic.configureOutput(includeContext=True, contextAbsPath=False)
>>>
>>> def foo():
>>>   ic(i)
>>> foo()
ic| example.py:18 in foo()- i: 3

contextAbsPath is False by default.

If you want to use icecream with multiple log levels, like with Python’s logging module, you can use ic.format() to integrate icecream’s debugging with your logger:

import logging
from icecream import ic

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

❕ This is a bit clunky. Would you prefer built-in log level support in icecream? If so, please share your thoughts in issue.

Installation

Installing IceCream with pip is easy.

$ pip install icecream

ic() uses executing by @alexmojaki to reliably locate ic() calls in Python source. It's magic.

IceCream in Other Languages

Delicious IceCream should be enjoyed in every language.

If you'd like a similar ic() function in your favorite language, please open a pull request! IceCream's goal is to sweeten print debugging with a handy-dandy ic() function in every language.

icecream (gruns/icecream)

Searching Database…

10.1K ·GitHub
这是干什么的?IceCream 是一个 Python 库,用来让打印调试更省心:不用 print(),而是调用 ic(),它会把每个表达式连同它的值一起打印出来,还带格式美化和语法高亮。
ic() 和直接用 print() 有什么区别?print() 只显示一个值;ic() 会把表达式和它的值一起打印,对数据结构做格式化输出,还会高亮显示。不带参数调用时,它会打印文件名、行号和所在函数,方便追踪代码执行。
怎么把它加到项目里?先用 pip 安装(pip install icecream),然后导入 ic,在原来想写 print() 的地方改用 ic() 就行。
除了 Python,还需要装别的东西吗?只需要一个 Python 3 或 PyPy3 解释器——其他什么都不用准备,pip 会连同依赖一起装好。
ic() 调用可以留在要上线的代码里吗?可以:ic() 会返回它的参数,所以已有代码里的调用不受影响;ic.disable() 能关掉输出,但调用照常返回,另外还有一段备用导入代码,可以在没装 IceCream 的环境里正常运行。
除了 Python,其他语言有没有类似 ic() 的东西?有。README 列出了 Dart、Rust、Node.js、C++、C99、PHP、Go、Ruby、Java、R、Lua、Clojure、Bash、SystemVerilog 和 GameMaker Language 的移植版本,目标是让每种语言都有 ic()。
ic() 是怎么知道我传进去的表达式原文的?它用了 Alex Mojaki 开发的 executing 库,能在 Python 源码里准确定位 ic() 调用——表达式本身就是这样被打印在值旁边的。
ic() 的输出能接进 logging 模块吗?目前还不能原生支持:README 建议用 ic.format(),它会把输出作为字符串返回,方便把调试信息交给你的日志记录器,作者也在征求关于内置日志级别支持的反馈。
Creator
gruns
Size
0.5 MB
Stars
10.1K
Age
8y
Commits · 90 Days