Repository: scipy/scipy
File: scipy/sparse/_base.py (Python)

Code before:

        out : np.matrix, optional
            Alternative output matrix in which to place the result. It must
            have the same shape as the expected output, but the type of the
            output values will be cast if necessary.

            .. versionadded:: 0.18.0

        Returns
        -------
        sum_along_axis : np.matrix
            A matrix with the same shape as `self`, with the specified
            axis removed.

        See Also
        --------
        numpy.matrix.sum : NumPy's implementation of 'sum' for matrices

        """
        axis = validateaxis(axis, ndim=self.ndim)

        # Mimic numpy's casting.
        res_dtype = get_sum_dtype(self.dtype)

        if dtype is not None:
            # Before casting to the requested dtype, caconicalize duplicates and zeros.
            if hasattr(self, 'sum_duplicates'):
                self.sum_duplicates()
            temp = self.astype(dtype, copy=False).sum(axis=axis, dtype=None, out=out)
            return temp.astype(dtype, copy=False)

        # Note: all valid 1D axis values are canonically `None`.
        if axis is None:
            if self.nnz == 0:
                return np.sum(self._ascontainer([0]), dtype=dtype or res_dtype, out=out)
            return np.sum(self._ascontainer(_todata(self)), dtype=dtype, out=out)
        elif isspmatrix(self):
            # Ensure spmatrix sums stay 2D
            new_shape = (1, self.shape[1]) if axis == (0,) else (self.shape[0], 1)
        else:
            new_shape = tuple(self.shape[i] for i in range(self.ndim) if i not in axis)

        if out is None:
            # create out array with desired dtype
            out = self._ascontainer(np.zeros(new_shape, dtype=dtype or res_dtype))
        else:
            if out.shape != new_shape:
                raise ValueError("out dimensions do not match shape")

        if self.ndim > 2:
            return self._sum_nd(axis, res_dtype, out)

Review comment (refactor):
```suggestion
            # Before casting to the requested dtype, canonicalize duplicates and zeros.
```

Code after:

        out : np.matrix, optional
            Alternative output matrix in which to place the result. It must
            have the same shape as the expected output, but the type of the
            output values will be cast if necessary.

            .. versionadded:: 0.18.0

        Returns
        -------
        sum_along_axis : np.matrix
            A matrix with the same shape as `self`, with the specified
            axis removed.

        See Also
        --------
        numpy.matrix.sum : NumPy's implementation of 'sum' for matrices

        """
        axis = validateaxis(axis, ndim=self.ndim)

        # Mimic numpy's casting.
        res_dtype = get_sum_dtype(self.dtype)

        if dtype is not None:
            # Before casting to the requested dtype, canonicalize duplicates and zeros.
            if hasattr(self, 'sum_duplicates'):
                self.sum_duplicates()
            temp = self.astype(dtype, copy=False).sum(axis=axis, dtype=None, out=out)
            return temp.astype(dtype, copy=False)

        # Note: all valid 1D axis values are canonically `None`.
        if axis is None:
            if self.nnz == 0:
                return np.sum(self._ascontainer([0]), dtype=dtype or res_dtype, out=out)
            return np.sum(self._ascontainer(_todata(self)), dtype=dtype, out=out)
        elif isinstance(self, sparray):
            new_shape = tuple(self.shape[i] for i in range(self.ndim) if i not in axis)
        else:
            # Ensure spmatrix sums stay 2D
            new_shape = (1, self.shape[1]) if axis == (0,) else (self.shape[0], 1)

        if out is None:
            # create out array with desired dtype
            out = self._ascontainer(np.zeros(new_shape, dtype=dtype or res_dtype))
        else:
            if out.shape != new_shape:
                raise ValueError("out dimensions do not match shape")

        if self.ndim > 2:
            return self._sum_nd(axis, res_dtype, out)