E AssertionError: assert {'a': 1.0, 'b': 2.0000000001} == {'a': 1.0, 'b': 2.0} E 省略 1 个相同项,使用 -vv 显示 E 差异项: E {'b': 2.0000000001 != 2.0}
E AssertionError: assert {'a': 1.0, 'b': 2.0000000001} == {'a': 1.0, 'b': 2.0} E Omitting 1 identical items, use -vv to show E Differing items: E {'b': 2.0000000001 != 2.0}
ID: python/assertionerror-dict-approx-ordering
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| 3.x | active | — | — | — |
| 7.x | active | — | — | — |
| 8.x | active | — | — | — |
根因分析
嵌套 dict/list 结构中的浮点比较失败,因为使用 == 比较时 pytest.approx 默认不会递归到容器内部;需要对整个结构或每个值使用 pytest.approx。
English
Float comparison inside nested dict/list structures fails because pytest.approx does not recurse into containers by default when comparing with ==; you must use pytest.approx on the whole structure or per-value.
解决方案
-
95% 成功率
from pytest import approx assert result == approx({'a': 1.0, 'b': 2.0}, rel=1e-6) # approx recurses into dicts and lists -
85% 成功率
def approx_dict(d, rel=1e-6): return {k: approx(v, rel=rel) if isinstance(v, float) else v for k, v in d.items()} assert result == approx_dict({'a': 1.0, 'b': 2.0})
无效尝试
常见但无效的做法:
-
60% 失败
Rounding both sides may still differ if the underlying computation drifts beyond the rounding boundary; it hides but does not fix the comparison semantics.
-
90% 失败
String formatting is locale- and precision-sensitive; dict ordering and repr differences cause flaky failures.