Skip to content

Better introspection for comparing numpy arrays #5347

Closed
@timhoffm

Description

@timhoffm

With plain python lists I can do:

a = [1, 2, 3]
b = [1, 2, 4]
assert a == b

That does not work for numpy arrays

        a = np.array([1, 2, 3])
        b = np.array([1, 2, 4])
>       assert a == b
E       ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

There are two ways out:

  • Using numpy.testing

    np.testing.assert_equal(a, b)
    

    This has the advantage of giving good context information on the error.
    But it is far from the simple assert assert a == b paradigm in pytest.

  • Alternatively we can aggregate the the check to a single bool

    assert np.all(a == b)
    

    This looks much nicer, but pytest cannot tell anymore where the error is:

    >       assert np.all(a == b)
    E       assert False
    E        +  where False = <function all at 0x7f57cd65eea0>(array([1, 2, 3]) == array([1, 2, 4])
    E        +    where <function all at 0x7f57cd65eea0> = np.all
    

Question: Would it in principle be possible with pytest's introspection capabilities to resolve the contents of np.all() and give a better error message? In a frist step maybe something like

assert np.all(a == b)
  At index 2: False

This of course, would require an assumption on the semantics of np.all.

Alternative idea: Could pytest be made to rewrite assert a == b to np.testing.assert_equal(a, b) if either a or b is a numpy array? Possibly not a good idea because it introduces a different semantic compared to a plain a == b.

Metadata

Metadata

Assignees

No one assigned

    Labels

    topic: reportingrelated to terminal output and user-facing messages and errorstopic: rewriterelated to the assertion rewrite mechanismtype: proposalproposal for a new feature, often to gather opinions or design the API around the new feature

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions