python data_error ai_generated true

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

Also available as: JSON · Markdown · 中文
80%Fix Rate
86%Confidence
0Evidence
2024-04-19First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
3.x active — — —
7.x active — — —
8.x active — — —

Root Cause

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

中文

嵌套 dict/list 结构中的浮点比较失败,因为使用 == 比较时 pytest.approx 默认不会递归到容器内部;需要对整个结构或每个值使用 pytest.approx。

Workarounds

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

Dead Ends

Common approaches that don't work:

  1. 60% fail

    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% fail

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