{"record":{"id":"0a68515ae8a245d8","repo":"pytest-dev/pytest","slug":"cannot-compare-actual-to-numpy-ndarray","errorCode":null,"errorMessage":"cannot compare '{actual}' to numpy.ndarray","messagePattern":"cannot compare '(.+?)' to numpy\\.ndarray","errorType":"exception","errorClass":"TypeError","httpStatus":null,"severity":"error","filePath":"src/_pytest/approx.py","lineNumber":227,"sourceCode":"        return _compare_approx(\n            self.expected,\n            message_data,\n            number_of_elements,\n            different_ids,\n            max_abs_diff,\n            max_rel_diff,\n        )\n\n    def __eq__(self, actual) -> bool:\n        import numpy as np\n\n        # self.expected is supposed to always be an array here.\n\n        if not np.isscalar(actual):\n            try:\n                actual = np.asarray(actual)\n            except Exception as e:\n                raise TypeError(f\"cannot compare '{actual}' to numpy.ndarray\") from e\n\n        if not np.isscalar(actual) and actual.shape != self.expected.shape:\n            return False\n\n        return super().__eq__(actual)\n\n    def _yield_comparisons(self, actual):\n        import numpy as np\n\n        # `actual` can either be a numpy array or a scalar, it is treated in\n        # `__eq__` before being passed to `ApproxBase.__eq__`, which is the\n        # only method that calls this one.\n\n        if np.isscalar(actual):\n            for i in np.ndindex(self.expected.shape):\n                yield actual, self.expected[i].item()\n        else:\n            for i in np.ndindex(self.expected.shape):","sourceCodeStart":209,"sourceCodeEnd":245,"githubUrl":"https://github.com/pytest-dev/pytest/blob/0d6fbdeffa57c796123f62f81f7dd370d9b7ecdc/src/_pytest/approx.py#L209-L245","documentation":"When approx() wraps a numpy array, ApproxNumpy.__eq__ tries to convert the compared value to an ndarray via np.asarray(actual). If that conversion raises any exception (the actual value is not array-like), pytest re-raises it as this TypeError, chaining the original cause. This protects the comparison from silently returning False on genuinely incompatible operands.","triggerScenarios":"Calling approx(np.array([1.0,2.0])) == some_object where some_object is a dict, a string, an object without __array__, or a ragged/nested structure numpy cannot broadcast. Triggered at ApproxNumpy.__eq__ (src/_pytest/approx.py:218-227) only when the expected value was itself a numpy array (or array-like with numpy imported).","commonSituations":"Comparing an array approximation against a dict/None/string; mixing array and scalar-with-mixed-types; passing an object that implements __array__ but raises internally; using a mock or custom container as the actual value.","solutions":["Ensure the actual value is array-like (list, tuple, or numpy array) before comparing: `assert np.asarray(actual) == approx(np.array([...]))`.","Convert both sides explicitly with np.asarray so the failure happens with a clearer traceback.","If comparing a single scalar to an array, compare against approx(scalar) instead of approx(array)."],"exampleFix":"# before\nassert {'a': 1} == approx(np.array([1.0, 2.0]))\n# after\nassert np.array([1.0, 2.0]) == approx(np.array([1.0, 2.0]))","handlingStrategy":"validation","validationCode":"import numpy as np\ndef is_array_compatible(value) -> bool:\n    if np.isscalar(value):\n        return True\n    try:\n        np.asarray(value)\n        return True\n    except Exception:\n        return False\n# usage\nif is_array_compatible(actual):\n    assert actual == approx(np_array)","typeGuard":"import numpy as np\ndef is_ndarray_or_scalar(v) -> bool:\n    return np.isscalar(v) or isinstance(v, np.ndarray)","tryCatchPattern":"try:\n    assert actual == approx(np_array)\nexcept TypeError as e:\n    if 'cannot compare' in str(e):\n        raise AssertionError(f'actual not array-like: {actual!r}') from e\n    raise","preventionTips":["Coerce actual with np.asarray before comparing to approx(array).","Avoid comparing approx(array) to dicts, strings, or None.","For scalar-vs-array, use approx(scalar) on the right side."],"tags":["pytest","approx","numpy","type-conversion","comparison"],"backgroundTag":null,"analyzedSha":"0d6fbdeffa57c796123f62f81f7dd370d9b7ecdc","analyzedAt":"2026-08-11T20:52:36.969Z","contentChangedAt":null,"schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}