Python 第三方库 Icecream 说明文档

Icecream 🍦 - 替代print()来调试程序。

再日常 Python 开发中,您是否使用 print()log() 来调试您的代码?我想,每个人都这样过。不过 Icecream 会让打印调试更”甜“一点。( Icecream 冰淇淋 )。
ic()Icecream 中的函数,就像print(),但是它更好:

  1. 它同时打印表达式/可变名称及其值。
  2. 输入速度快了 40% (说白了就是字节数)。
  3. 数据结构打印得好。
  4. 输出突出显示语法。
  5. 它可选地包括程序上下文: 文件名、行号和父功能。

另外,作为第三方库,Iceream 经过充分的测试, 支持 Python 2、Python 3、PyPy2 和 PyPy3。可以无轻松的学习和开发。

检查变量 ( Inspect Variable )

您是否曾经打印变量或表达式来调试程序?如果你曾经写过类似的东西。

print(foo('123'))``

或者更彻底?

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

ic()在这里提供帮助。通过参数,ic() 检查自身并打印其自身的参数和这些参数的值。

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)

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

只要给 ic() 一个变量或表达式,你就完成了任务,多简单!

检查执行 ( Inspect Execution )

您是否使用过print()来确定执行程序的哪些部分以及执行这些部分的顺序?例如,如果您曾经在调试代码中添加过打印语句,例如

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

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

ic()也可以在这里提供帮助。在没有参数的情况下,ic()检查自身并打印文件名、行号和父函数。

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()

只要引用ic(),就可以轻松的完成预期任务,很简单。

返回值 ( Return Value )

ic()可以返回输入程序的原本格式,因此可以轻松地将其插入预先存在的代码中。

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

杂项 ( Miscellaneous )

ic.format(*args)就像ic(),输出是字符串的形式,而不会引发让人莫名其妙的written to STDERR异常。

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

此外,ic() 的输出可以完全禁用,然后重新启用,分别使用 ic.disable()ic.enable()

from icecream import ic

ic(1)
ic.disable()

ic(2)
ic.enable()
ic(3)
Prints
ic| 1: 1
ic| 3: 3

当然,在 ic() 禁用时,ic()会继续接受参数,他不会输出也不会对其他代码产生影响。

导入技巧 ( Import Tricks )

要使每个文件中都可用,而无需在每个文件中导入,您可以安装它( install() )。例如,在A.py中:

#!/usr/bin/env python3

from icecream import install
install()

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

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

将ic()添加到内置模块中,该模块在码农导入的所有文件之间共享。同样,ic() 以后也可以卸载( uninstall() )。
如果未安装Icecream(如在生产环境中(即未开发)),也可以以优雅方式导入。为此,此回退导段可能证明是有用的:

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() 配置输出(前缀、输出功能、参数串联功能、包括文本)可用于采用自定义输出前缀,默认值为 ic(),更改输出函数(默认值是写到stderr),自定义参数如何序列化为字符串,和/或将ic()呼叫的上下文(文件名、行号和父函数)包含在带有参数的ic输出中。

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

hello -> 'world'
prefix can optionally be a function, too.


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

1519185860 |> 'world': 'world'
outputFunction, if provided, is called with ic()'s output instead of that output being written to stderr (the default).

>>> import logging
>>> from icecream import ic
>>>
>>> def warn(s):
>>>     logging.warning(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!]
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():
>>>   ic('str')
>>> foo()

ic| example.py:12 in foo()- 'str': 'str'

包括默认情况下的"文本错误"。
安装( Installation )

在pip中安装 Icecream 是很容易的。

$ pip install icecream

相关 Python 库 ( Related Python libraries )

ic() 使用了Alex Hallexecuting 库,您可以可靠地定位Python源中的ic()命令。

icecream在其他语言也应该被”享受”。

语言链接
Python icecream
Dart icecream
Rusticecream-rs
Node.jsnode-icecream
C++IceCream-Cpp
C99 icecream-c
PHPicecream-php
Goicecream-go
RubyRicecream
Javaicecream-java
R icecream
Luaicecream-lua
Clojure(Script)icecream-cljc

如果您想在您最喜爱的语言中使用类似的 ic() 功能,请打开拉取请求!IceCream 的目标是在每种语言中使用方便的ic()功能来”甜化”打印调试。

以上为译文(英 译 中)。
原文 Github - Icecream

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值