{"id":"edcf92cb9d366e2a","repo":"pytest-dev/pytest","slug":"pytest-approx-does-not-support-nested-data-struc","errorCode":null,"errorMessage":"pytest.approx() does not support nested data structures: {!r} at index {}\n  full sequence: {}","messagePattern":"pytest\\.approx\\(\\) does not support nested data structures: (.+?) at index (.+?)\n  full sequence: (.+?)","errorType":"exception","errorClass":"TypeError","httpStatus":null,"severity":"error","filePath":"src/_pytest/approx.py","lineNumber":363,"sourceCode":"            yield actual[k], self.expected[k]\n\n\nclass ApproxSequenceLike(Approx[Sequence[Any]]):\n    \"\"\"Perform approximate comparisons where the expected value is a sequence of numbers.\"\"\"\n\n    def __init__(\n        self,\n        expected: Sequence[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 index, x in enumerate(expected):\n            if isinstance(x, type(expected)):\n                msg = \"pytest.approx() does not support nested data structures: {!r} at index {}\\n  full sequence: {}\"\n                raise TypeError(msg.format(x, index, pprint.pformat(expected)))\n\n        super().__init__(expected, rel=rel, abs=abs, nan_ok=nan_ok)\n\n    def __repr__(self) -> str:\n        seq_type = type(self.expected)\n        if seq_type not in (tuple, list):\n            seq_type = list\n        return f\"approx({seq_type(self._approx_scalar(x) for x in self.expected)!r})\"\n\n    def _repr_compare(self, other_side: Sequence[float]) -> list[str]:\n        import math\n\n        if len(self.expected) != len(other_side):\n            return [\n                \"Impossible to compare lists with different sizes.\",\n                f\"Lengths: {len(self.expected)} and {len(other_side)}\",\n            ]\n","sourceCodeStart":345,"sourceCodeEnd":381,"githubUrl":"https://github.com/pytest-dev/pytest/blob/98b357f69e380da908740a212288d73b2ee06687/src/_pytest/approx.py#L345-L381","documentation":"pytest.approx() does not support nested sequences (lists/tuples within lists). When ApproxSequenceLike.__init__ iterates the expected sequence, if any element is itself an instance of the same sequence type, pytest raises TypeError. approx() only compares flat sequences of numbers.","triggerScenarios":"Calling approx([[1.0, 2.0], [3.0, 4.0]]). The element [1.0, 2.0] is a list, isinstance(x, type(expected)) is True, so TypeError is raised.","commonSituations":"Comparing 2D matrices, batches of results, or nested arrays where the developer expects element-wise tolerance comparison at all depths.","solutions":["Use numpy arrays with approx for multi-dimensional data: assert np.array_equal(actual, approx(expected_array)).","Compare each sub-sequence individually with a loop.","Flatten the nested structure if the comparison is semantically flat."],"exampleFix":"# before\nassert result == approx([[1.0, 2.0], [3.0, 4.0]])\n\n# after\nimport numpy as np\nassert np.allclose(result, [[1.0, 2.0], [3.0, 4.0]])","handlingStrategy":"type-guard","validationCode":"from collections.abc import Sequence\n\ndef is_flat_numeric_sequence(seq: Sequence) -> bool:\n    \"\"\"Check that a sequence contains no nested sequences (suitable for approx()).\"\"\"\n    return all(not isinstance(x, type(seq)) for x in seq)\n\n# usage:\n# assert is_flat_numeric_sequence(expected), 'approx() requires a flat list; use numpy for 2D data'","typeGuard":"from collections.abc import Sequence\n\ndef is_approx_compatible_sequence(value) -> bool:\n    return isinstance(value, Sequence) and not isinstance(value, (str, bytes)) and all(\n        not isinstance(x, type(value)) for x in value\n    )","tryCatchPattern":null,"preventionTips":["Use numpy arrays with np.allclose or approx(np.array(...)) for multi-dimensional data.","Flatten 2D lists to 1D if the comparison is semantically flat.","Compare sub-lists individually in a loop for nested sequences."],"tags":["approx","sequence","type-error","nested-structures","numpy"],"analyzedSha":"98b357f69e380da908740a212288d73b2ee06687","analyzedAt":"2026-08-04T20:26:34.442Z","schemaVersion":2}