Skip to content

BUG: assert_equal/assert_array_equal now handle NaN in object arrays (gh-9023) - #32661

Open
BHUVANSH855 wants to merge 1 commit into
numpy:mainfrom
BHUVANSH855:fix-9023-object-nan
Open

BHUVANSH855 wants to merge 1 commit into
numpy:mainfrom
BHUVANSH855:fix-9023-object-nan

Conversation

@BHUVANSH855

@BHUVANSH855 BHUVANSH855 commented Sep 16, 2026

Copy link
Copy Markdown
Contributor

PR summary

numpy.testing.assert_equal and assert_array_equal raise a spurious AssertionError when comparing dtype=object arrays containing NaN values in matching positions, even though the two arrays are otherwise identical:

>>> import numpy as np
>>> from numpy.testing import assert_equal
>>> a = np.array([1, 2, np.nan], dtype=object)
>>> assert_equal(a, a)
AssertionError:
Arrays are not equal
(mismatch 33.33333333333333%)

This closes gh-9023. assert_equal/assert_array_equal already treat matching-position NaNs as equal for numeric dtypes (via a NaN-position check in assert_array_compare), but that check is gated by an isnumber(x) and isnumber(y) condition that excludes dtype=object arrays entirely, so dtype=object arrays fall through to a plain == comparison, and nan != nan under IEEE-754 semantics then triggers a false mismatch.

This PR adds an isobject(x) and isobject(y) branch to assert_array_compare, parallel to the existing branches for
numeric, time, and vstring dtypes. Since np.isnan doesn't support dtype=object, NaN-detection for this branch uses each element's self-inequality (v != v), guarded with a try/except so non-comparable objects don't raise.

Scope note: assert_allclose on dtype=object arrays has a related but distinct failure (TypeError from isfinite not
supporting dtype=object, reported in gh-25496). That failure occurs even on object arrays with no NaN at all, since it comes from np.isclose's internal use of isfinite, not from the NaN-position gating this PR touches. Fixing it would require changes to np.isclose itself or a fallback path in assert_allclose's compare(), which is out of scope here — I've left it for gh-25496.

A regression test (test_object_array_nan_items) is added, verifying both that matching-NaN object arrays compare equal and that a genuine mismatch is still correctly caught.

First time contributor introduction

Started contributing to NumPy a few days ago, and main aim it to learn more, enhance my knowledge and to help team to clear their issue triaging backlog.

AI Disclosure

No AI tool is used.

sylvesterkaczmarek

This comment was marked as low quality.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

BUG: assert_equal fails on object arrays of nan

2 participants