Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/353.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 完成脚本中的断言?_Python_Function_Assertion - Fatal编程技术网

Python 完成脚本中的断言?

Python 完成脚本中的断言?,python,function,assertion,Python,Function,Assertion,我刚刚完成了图像的卷积脚本 现在,我的函数如下所示: def conv(图像:np.ndarray, conv:np.ndarray,*args): 断言1

我刚刚完成了图像的卷积脚本

现在,我的函数如下所示:

def conv(图像:np.ndarray,
conv:np.ndarray,*args):
断言1
如果这些断言中的任何一个不满足,那么输入是错误的,并且很可能函数会给出一个错误

尽管如此,用户将无法理解什么是错误的,加上延迟,直到它到达错误

在我读到的所有地方,
assert
都用于调试。每次运行我的算法时,是否最好“放慢”速度,而不是放慢速度和未记录的错误(他必须参考docstring)?在这些情况下最常见的做法是什么?

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

您可以
引发异常
,并简要说明发生异常的原因,例如,在您的案例中,您可以:

if not 1 < image.ndim < 4:
    raise Exception("Incorrect number of dimensions")
如果不是1
而不是

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

注意
不是
(条件的否定)。有关更多数据,请参阅。

谢谢。还有一个问题。这种做法是惯例还是有助于提高绩效?(我已经多次读到“not”语句会减慢过程)@CommissarVasiliKarlovic您可以决定用
not
-less风格重写您的条件,例如
if image.ndim=4:
,但我不会忽略其中的巨大差异。我建议看一下模块,它允许测试代码执行的速度。