ImportError:无法导入名称“ isclose”

时间:2018-07-07 05:01:57

标签: python math travis-ci python-3.4 pytest

在对Python模块进行单元测试时,我遇到了一个奇怪的错误:

⅔个构建正常通过,但是其中一个无法从标准isclose库导入math

该错误再现如下:

==================================== ERRORS ====================================
______________________ ERROR collecting tests/test_yau.py ______________________
ImportError while importing test module '/home/travis/build/Benjamin-Lee/squiggle/tests/test_yau.py'.
Hint: make sure your test modules/packages have valid Python names.
Traceback:
tests/test_yau.py:5: in <module>
    from math import isclose
E   ImportError: cannot import name 'isclose'
!!!!!!!!!!!!!!!!!!! Interrupted: 1 errors during collection !!!!!!!!!!!!!!!!!!!!
=========================== 1 error in 0.29 seconds ============================
The command "pytest --cov=squiggle" exited with 2.

在同一目录中(或在我的软件包中)没有名为math.py的文件。可能是什么原因造成的?

多次重新启动构建并不能解决此错误,它仅在Python 3.4中显示。

完整的日志可以访问here

2 个答案:

答案 0 :(得分:3)

正如我们从链接的“完整日志”中看到的那样,您正在运行Python 3.4.6。

https

math.isclose函数was introduced in Python 3.5,这就是为什么您不能导入它的原因。安装更高版本的Python(即3.5+),或定义自己的$ python --version Python 3.4.6 函数,isclose模块的定义几乎如下所示:

math
  

def isclose(a, b, rel_tol=1e-9, abs_tol=0.0): return abs(a-b) <= max(rel_tol * max(abs(a), abs(b)), abs_tol) # tests: print(0.1 + 0.2) print(0.1 + 0.2 == 0.3) print(isclose(0.1 + 0.2, 0.3)) # outputs: 0.30000000000000004 False True a:是要测试的相对亲和力的两个值

     

b:是相对公差-它是误差量   相对于rel_tola的较大绝对值。例如,   要将公差设置为5%,请通过b。默认公差为   1e-9,这可以确保两个值在大约9之间是相同的   十进制数字。 rel_tol=0.05必须大于0.0

     

rel_tol:是最低绝对公差水平-对   比较接近零。

答案 1 :(得分:3)

pytest具有函数approx,用于测试两个数字的近似相等性,可用于任何python版本。断言

assert math.isclose(a, b, rel_tol=rt, abs_tol=at)

因此可以替换为

assert a == pytest.approx(b, rel=rt, abs=at)