Skip to content

BUG: numpy.convolve raises misleading ValueError on empty inputs due to internal variable swapping #30272

@scsukas8

Description

@scsukas8

Describe the issue:

Minor incorrect error message:

In the convolve() function, if len(a) == 0 and len(v) > 0, the function will swap a and v, then return "v cannot be empty".

Relevant Code (Ref)

    if (len(v) > len(a)):
        a, v = v, a
    if len(a) == 0:
        raise ValueError('a cannot be empty')
    if len(v) == 0:
        raise ValueError('v cannot be empty')

Practically, this means if your first argument to convolve is empty, it will often incorrectly raise an error that says your second argument is empty.

Reproduce the code example:

import numpy as np

a = np.array([])      # Empty
v = np.array([1, 2])  # Not empty

# This triggers the swap, and internal state becomes: a=[1, 2], v=[]
#  Raises "v cannot be empty"
np.convolve(a, v)

Error message:

ERROR!
Traceback (most recent call last):
  File "<main.py>", line 8, in <module>
  File "/usr/local/lib/python3.12/site-packages/numpy/_core/numeric.py", line 902, in convolve
    raise ValueError('v cannot be empty')
ValueError: v cannot be empty

Python and NumPy Versions:

v2.3.0

Runtime Environment:

No response

Context for the issue:

Working in jax, I wasted a hour trying to figure out how my second argument could possibly be empty. Eventually I realized numpy was pointing me to the wrong argument and found my bug in the first array.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions