{"record":{"id":"61fe9959e9e59bf9","repo":"pytest-dev/pytest","slug":"pytest-approx-does-not-support-nested-dictionari","errorCode":null,"errorMessage":"pytest.approx() does not support nested dictionaries: key={!r} value={!r}\n  full mapping={}","messagePattern":"pytest\\.approx\\(\\) does not support nested dictionaries: key=(.+?) value=(.+?)\n  full mapping=(.+?)","errorType":"exception","errorClass":"TypeError","httpStatus":null,"severity":"error","filePath":"src/_pytest/approx.py","lineNumber":265,"sourceCode":"\n\nclass ApproxMapping(Approx[Mapping[Any, Any]]):\n    \"\"\"Perform approximate comparisons where the expected value is a mapping\n    with numeric values (the keys can be anything).\"\"\"\n\n    def __init__(\n        self,\n        expected: Mapping[Any, Any],\n        rel: float | Decimal | timedelta | None,\n        abs: float | Decimal | timedelta | None,\n        nan_ok: bool,\n    ) -> None:\n        __tracebackhide__ = True\n\n        for key, value in expected.items():\n            if isinstance(value, type(expected)):\n                msg = \"pytest.approx() does not support nested dictionaries: key={!r} value={!r}\\n  full mapping={}\"\n                raise TypeError(msg.format(key, value, pprint.pformat(expected)))\n\n        super().__init__(expected, rel=rel, abs=abs, nan_ok=nan_ok)\n\n    def __repr__(self) -> str:\n        return f\"approx({ ({k: self._approx_scalar(v) for k, v in self.expected.items()})!r})\"\n\n    def _repr_compare(self, other_side: Mapping[object, float]) -> list[str]:\n        import math\n\n        if len(self.expected) != len(other_side):\n            return [\n                \"Impossible to compare mappings with different sizes.\",\n                f\"Lengths: {len(self.expected)} and {len(other_side)}\",\n            ]\n\n        if self.expected.keys() != other_side.keys():\n            return [\n                \"comparison failed.\",","sourceCodeStart":247,"sourceCodeEnd":283,"githubUrl":"https://github.com/pytest-dev/pytest/blob/0d6fbdeffa57c796123f62f81f7dd370d9b7ecdc/src/_pytest/approx.py#L247-L283","documentation":"ApproxMapping.__init__ walks the expected dict and rejects any value whose type matches the expected mapping's own type (i.e. a nested dict of the same kind). pytest does this because its recursive comparison model only handles one level of mapping; nested mappings would produce ambiguous/incorrect tolerance results. The error names the offending key, value, and pretty-prints the full mapping for diagnosis.","triggerScenarios":"Calling approx({'outer': {'inner': 1.0}}) or approx(defaultdict(... nested defaultdict ...)). Also triggered by custom Mapping subclasses where a value is the same Mapping type. Triggered at ApproxMapping.__init__ (src/_pytest/approx.py:262-265).","commonSituations":"Comparing JSON-decoded nested objects, configuration trees, or sensor readings grouped by category; refactoring flat dicts into nested ones without updating the assertion.","solutions":["Flatten the nested dict before comparison, or compare each sub-dict separately with its own approx() call.","Restructure the expected data so numeric values live at the top level.","For deeply nested numeric trees, write a recursive helper that applies approx() at each level."],"exampleFix":"# before\nassert result == approx({'a': {'b': 0.3}})\n# after\nassert result['a'] == approx({'b': 0.3})","handlingStrategy":"validation","validationCode":"def is_flat_numeric_mapping(d: dict) -> bool:\n    return all(not isinstance(v, dict) for v in d.values())\n# usage\nif is_flat_numeric_mapping(expected):\n    assert actual == approx(expected)\nelse:\n    # flatten or compare per-key\n    ...","typeGuard":"from collections.abc import Mapping\ndef is_flat_mapping(obj) -> bool:\n    return isinstance(obj, Mapping) and all(\n        not isinstance(v, Mapping) for v in obj.values()\n    )","tryCatchPattern":null,"preventionTips":["Keep approx() dicts single-level; compare nested dicts per-key.","Flatten nested JSON before passing to approx().","For nested numeric trees, write a recursive approx helper."],"tags":["pytest","approx","dict","nested-structure","mapping"],"backgroundTag":null,"analyzedSha":"0d6fbdeffa57c796123f62f81f7dd370d9b7ecdc","analyzedAt":"2026-08-11T20:52:36.969Z","contentChangedAt":null,"schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}