Compare (assert equality of) two complex data structures containing numpy arrays in unittest

后端 未结 7 1765
醉酒成梦
醉酒成梦 2020-12-06 16:25

I use Python\'s unittest module and want to check if two complex data structures are equal. The objects can be lists of dicts with all sorts of values: numbers,

7条回答
  •  一个人的身影
    2020-12-06 16:47

    So the idea illustrated by jterrace seems to work for me with a slight modification:

    class SaneEqualityArray(np.ndarray):
        def __eq__(self, other):
            return (isinstance(other, np.ndarray) and self.shape == other.shape and 
                np.allclose(self, other))
    

    Like I said, the container with these objects should be on the left side of the equality check. I create SaneEqualityArray objects from existing numpy.ndarrays like this:

    SaneEqualityArray(my_array.shape, my_array.dtype, my_array)
    

    in accordance with ndarray constructor signature:

    ndarray(shape, dtype=float, buffer=None, offset=0,
            strides=None, order=None)
    

    This class is defined within the test suite and serves for testing purposes only. The RHS of the equality check is an actual object returned by the tested function and contains real numpy.ndarray objects.

    P.S. Thanks to the authors of both answers posted so far, they were both very helpful. If anyone sees any problems with this approach, I'd appreciate your feedback.

提交回复
热议问题