15

Numpy has a very powerful broadcasting mechanism. It can even add 1x2 and 2x1 array without any warning. I don't like such behaviour: with 99% percent probability such addition is a consequence of my error and I want an exception to be thrown. The question: is there something like:

numpy.safe_add(A,B)

that works only when A and B have exactly the same shape?

2
  • "with 99% percent probability such addition is a consequence of my error and I want an exception to be thrown" - you're either not using broadcasting enough, or not noticing when you do. That said, it's reasonable to want a way to detect errors. Dec 27, 2013 at 9:25
  • I benefit from broadcasting a lot, for example it's cool that I can add 3x3 and 3x1 arrays. But sometimes I want safe universal functions.
    – Rizar
    Dec 28, 2013 at 10:19

1 Answer 1

7

You can define a subclass of ndarray that checks the shape of the result after the calculation. The calculation is executed, and we check the shape of the result, if it's not the same shape as the operand, an exception is raised:

import numpy as np

class NoBCArray(np.ndarray):

    def __new__(cls, input_array, info=None):
        obj = np.asarray(input_array).view(cls)
        return obj

    def __array_wrap__(self, out_arr, context=None):
        if self.shape != out_arr.shape:
            raise ValueError("Shape different")
        return np.ndarray.__array_wrap__(self, out_arr, context)

a = NoBCArray([[1, 2]])
b = NoBCArray([[3], [4]])

a + b # this will raise error

If you want to check before the calculation, you need wrap __add__:

def check_shape(opfunc):
    def checkopfunc(self, arr):
        if self.shape != arr.shape:
            raise ValueError("Shape different before calculation")
        else:
            return opfunc(self, arr)
    return checkopfunc

class NoBCArray(np.ndarray):

    __add__ = check_shape(np.ndarray.__add__)
1
  • 1
    The __array_wrap__ solution won't detect if you add a 2-by-3 array to a 1-by-3, since it checks the output's shape, rather than the other operand. Dec 27, 2013 at 9:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.