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

Code before:

    M = max([min(m + offset, n - offset) + max(0, offset)
             for offset in offsets])
    M = max(0, M)
    data_arr = np.zeros((len(offsets), M), dtype=dtype)

    K = min(m, n)

    for j, diagonal in enumerate(diagonals):
        offset = offsets[j]
        k = max(0, offset)
        length = min(m + offset, n - offset, K)
        if length < 0:
            raise ValueError(f"Offset {offset} (index {j}) out of bounds")
        try:
            data_arr[j, k:k+length] = diagonal[...,:length]
        except ValueError as e:
            if len(diagonal) != length and len(diagonal) != 1:
                raise ValueError(
                    f"Diagonal length (index {j}: {len(diagonal)} at"
                    f" offset {offset}) does not agree with array size ({m}, {n})."
                ) from e
            raise

    return dia_array((data_arr, offsets), shape=(m, n)).asformat(format)


def diags(diagonals, offsets=0, shape=None, format=None, dtype=None):
    """
    Construct a sparse matrix from diagonals.

    .. warning::

        This function returns a sparse matrix -- not a sparse array.
        You are encouraged to use `diags_array` to take advantage
        of the sparse array functionality.

    Parameters
    ----------
    diagonals : sequence of array_like
        Sequence of arrays containing the matrix diagonals,
        corresponding to `offsets`.
    offsets : sequence of int or an int, optional
        Diagonals to set (repeated offsets are not allowed):
          - k = 0  the main diagonal (default)
          - k > 0  the kth upper diagonal
          - k < 0  the kth lower diagonal
    shape : tuple of int, optional
        Shape of the result. If omitted, a square matrix large enough
        to contain the diagonals is returned.
    format : {"dia", "csr", "csc", "lil", ...}, optional

Review comment (suggestion):
minor nit: the else branched could be pulled out as being unconditional before the `if sys.version_info < (3, 12)`.

Code after:
        raise ValueError("Different number of diagonals and offsets.")

    # Determine shape, if omitted
    if shape is None:
        m = len(diagonals[0]) + abs(int(offsets[0]))
        shape = (m, m)

    # Determine data type, if omitted
    if dtype is None:
        dtype = np.result_type(*diagonals)
    elif dtype is _NoValue:
        # This is the old deprecated behavior that uses np.common_type().
        # After the deprecation period, this elif branch can be removed,
        # and the default for the `dtype` parameter changed back to `None`.
        dtype = np.dtype(np.common_type(*diagonals))
        future_dtype = np.result_type(*diagonals)
        if sys.version_info < (3, 12):
            warn_kwargs = {'stacklevel': 2}
            extra_msg = ("\nNote: In Python 3.11, this warning can be generated by "
                         "a call of scipy.sparse.diags(), but the code indicated in "
                         "the warning message will refer to an internal call of "
                         "scipy.sparse.diags_array(). If that happens, check your "
                         "code for the use of diags().")
        else:
            warn_kwargs = {'skip_file_prefixes': (os.path.dirname(__file__),)}
            extra_msg = ""
        if (dtype != future_dtype):
            warnings.warn(
                f"Input has data type {future_dtype}, but the output has been cast "
                f"to {dtype}.  In the future, the output data type will match the "
                "input. To avoid this warning, set the `dtype` parameter to `None` "
                "to have the output dtype match the input, or set it to the "
                "desired output data type."
                + extra_msg,
                FutureWarning,
                **warn_kwargs
            )

    # Construct data array
    m, n = shape

    M = max([min(m + offset, n - offset) + max(0, offset)
             for offset in offsets])
    M = max(0, M)
    data_arr = np.zeros((len(offsets), M), dtype=dtype)

    K = min(m, n)

    for j, diagonal in enumerate(diagonals):
        offset = offsets[j]
        k = max(0, offset)