{"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/98b357f69e380da908740a212288d73b2ee06687/src/_pytest/approx.py#L247-L283","documentation":"pytest.approx() does not support nested dictionaries. When ApproxMapping.__init__ iterates the expected mapping, if any value is itself an instance of the same mapping type (e.g., a dict value that is also a dict), pytest raises TypeError. This is a design limitation because approx() only compares flat numeric values.","triggerScenarios":"Calling approx({'a': 1.0, 'b': {'c': 2.0}}). The value for key 'b' is a dict, isinstance(value, type(expected)) is True, so TypeError is raised.","commonSituations":"Comparing nested API responses, config dicts, or JSON-like structures that contain sub-dictionaries with floats.","solutions":["Flatten the dictionary before comparison, or compare sub-dicts separately.","Use a manual recursive comparison helper for nested structures.","Extract and compare only the numeric leaf values with individual approx() calls."],"exampleFix":"# before\nassert result == approx({'a': 1.0, 'b': {'c': 2.0}})\n\n# after\nassert result['a'] == approx(1.0)\nassert result['b']['c'] == approx(2.0)","handlingStrategy":"type-guard","validationCode":"from collections.abc import Mapping\n\ndef is_flat_numeric_mapping(d: Mapping) -> bool:\n    \"\"\"Check that a mapping has no nested mappings (suitable for approx()).\"\"\"\n    return all(not isinstance(v, Mapping) for v in d.values())\n\n# usage:\n# assert is_flat_numeric_mapping(expected), 'approx() requires a flat dict; flatten nested dicts first'","typeGuard":"from collections.abc import Mapping\n\ndef is_approx_compatible_mapping(value) -> bool:\n    return isinstance(value, Mapping) and all(\n        not isinstance(v, Mapping) for v in value.values()\n    )","tryCatchPattern":null,"preventionTips":["Flatten nested dicts before passing to approx(), or compare each sub-dict separately.","For deeply nested structures (e.g., JSON responses), write a custom recursive approx comparison."],"tags":["approx","dict","type-error","nested-structures"],"analyzedSha":"98b357f69e380da908740a212288d73b2ee06687","analyzedAt":"2026-08-04T20:26:34.442Z","schemaVersion":2}