Skip to content

Fix assert_almost_equal, add test #48920

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 7 additions & 1 deletion pandas/_libs/testing.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,13 @@ from pandas.core.dtypes.missing import (


cdef bint isiterable(obj):
return hasattr(obj, '__iter__')
if hasattr(obj, '__iter__'):
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm not completely convinced this is an appropriate fix to simply exclude 0-D arrays here. This might have unintended consequences where we want to treat 0-D arrays as iterable.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I've changed it to use try/except. Is this an appropiate fix?

try:
iter(obj)
return True
except (TypeError, IndexError) as e:
return False
return False


cdef bint has_length(obj):
Expand Down
3 changes: 3 additions & 0 deletions pandas/tests/dtypes/test_inference.py
Original file line number Diff line number Diff line change
Expand Up @@ -126,6 +126,9 @@ def size(self):
def shape(self):
return self._values.shape

def __getitem__(self, item):
return self._values[item]


# collect all objects to be tested for list-like-ness; use tuples of objects,
# whether they are list-like or not (special casing for sets), and their ID
Expand Down
14 changes: 14 additions & 0 deletions pandas/tests/util/test_assert_almost_equal.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
Timestamp,
)
import pandas._testing as tm
from pandas.tests.dtypes.test_inference import MockNumpyLikeArray


def _assert_almost_equal_both(a, b, **kwargs):
Expand Down Expand Up @@ -458,3 +459,16 @@ def test_assert_almost_equal_iterable_values_mismatch():

with pytest.raises(AssertionError, match=msg):
tm.assert_almost_equal([1, 2], [1, 3])


@pytest.mark.parametrize(
"obj",
[
MockNumpyLikeArray(np.ndarray((2,) * 1)),
MockNumpyLikeArray(np.array([])),
MockNumpyLikeArray(np.array(2)),
],
ids=["duck-ndarray-1d", "duck-ndarray-1d-empty", "duck-ndarray-0d"],
)
def test_assert_almost_equal_not_iterable(obj):
tm.assert_almost_equal(obj, obj)