python data_error ai_generated true

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

其他格式: JSON · Markdown 中文 · English
80%修复率
86%置信度
0证据数
2024-04-19首次发现

版本兼容性

版本状态引入弃用备注
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.

generic

解决方案

  1. 95% 成功率
    from pytest import approx
    assert result == approx({'a': 1.0, 'b': 2.0}, rel=1e-6)
    # approx recurses into dicts and lists
  2. 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})

无效尝试

常见但无效的做法:

  1. 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.

  2. 90% 失败

    String formatting is locale- and precision-sensitive; dict ordering and repr differences cause flaky failures.