python - 断言某些东西是 Python 中的有效函数

标签 python unit-testing

假设我有以下代码,它接受一个距离函数和两个点,并吐出距离:

def distance(dist_fun, p1, p2):
    ## SOME ASSERTION HERE on dist_fun ##

    ## Suppose, just for this post, we've already checked p1 and p2 are 
    ## n-tuples of integers.

    assert (len(p1) == len(p2)), "Coordinates are different dimensions."
    dist = dist_fun(p1, p2)
    assert (dist>=0), "Negative distance is not possible."
    return dist

def euclid(p1, p2):  #as an example dist function.
    return pow(reduce(lambda x,y: x+y, [pow((p1[i] - p2[i]), 2) for i in range(len(p1))]),0.5)

我希望能够检查用户是否使用了特定的距离函数,首先,它实际上是一个函数。在此之后,我可以检查其他内容,但我的主要问题是:我如何断言 dist_fun 实际上是一个函数?

如果没有简单的方法可以做到这一点,或者如果有其他方法可以做到这一点,请告诉我。我以前用 Python 做过一些测试,但直到现在才遇到这个问题。我已经看到函数的“类型”是“函数”,但是 Python 不允许我将其用作类型?回到这里尝试会更容易吗?

最佳答案

当然,Python 的座右铭是请求宽恕比请求许可更好。因此,您完全可以指望用户向您传递有效输入,或者 except 如果您尝试调用无法调用的内容,则会抛出 TypeError叫做。

话虽这么说,如果你真的想断言某物是一个函数,我想你总是可以检查类型...

assert (callable(dist_fun))

关于python - 断言某些东西是 Python 中的有效函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20578910/

相关文章:

python - Ansible - 从字典中获取一个键(但不是在循环中)

python - pd.cut 类别为 plt.xticklabels

python - 有没有办法在 python 中对具有不匹配索引的数组进行子集化?

python - 为什么要这样枚举呢?

c++ - Google Mock - 如何使用 EXPECT_CALL 返回不同的值以退出循环

java - 将模拟 bean 注入(inject) spring 上下文进行测试

python - TensorFlow 中的默认 tf.gradients - 全导数还是偏导数?

python - 如何通过 slack API 删除/禁用用户?

c# - 使用 Nunit TestCaseSource 运行测试设置的正确方法

php - 单元测试和对象继承