【问题标题】:Assertions in a finished script?完成脚本中的断言?
【发布时间】:2020-06-20 19:10:38
【问题描述】:

我刚刚完成了一个图像卷积脚本。

现在,我的函数看起来像:

def conv(image: np.ndarray,
         conv: np.ndarray, *args):

    assert 1 < image.ndim < 4, "error0"
    assert conv.ndim is 2, "error1"
    xconv, yconv = conv.shape
    assert xconv == yconv and xconv % 2, "error2"
    # computations

如果这些断言中的任何一个不满足,那么输入是错误的,很可能函数会出错。

虽然,用户将无法理解问题所在,再加上到达错误之前的延迟。

我在任何地方都读到assert 用于调试。每次运行时“减慢”我的算法而不是更慢和未记录的错误(他必须参考文档字符串)会更好吗?在这些情况下,最常见的做法是什么?

【问题讨论】:

    标签: python function assertion


    【解决方案1】:

    在这些情况下最常见的做法是什么?

    您可以 raise Exception 简要说明它发生的原因,因此以您为例,您可以这样做:

    if not 1 < image.ndim < 4:
        raise Exception("Incorrect number of dimensions")
    

    而不是

    assert 1 < image.ndim < 4, "error0"
    

    注意not(否定条件)。更多数据见docs fo Errors and Exceptions

    【讨论】:

    • 谢谢。还有一个问题。这种做法是惯例还是对性能有帮助? (我读过很多次“not”语句会减慢进程)
    • @CommissarVasiliKarlovic 您可以决定以not-less 样式重写您的条件,例如if image.ndim &lt;=1 or image.ndim &gt;=4:,但我不会有很大的不同。我建议看看timeit 模块,它可以测试代码执行的速度。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-05
    相关资源
    最近更新 更多