array-api icon indicating copy to clipboard operation
array-api copied to clipboard

Iteration on 1-D arrays

Open asmeurer opened this issue 6 days ago • 9 comments

Recently in array-api-strict, I accidentally disabled iteration on 1-D arrays. This broke a lot of code in SciPy. I've since reverted the change (array-api-strict disallows iteration on >1-D arrays but allows it for 1-D arrays).

There have been discussions in the past about now allowing iteration on arrays https://github.com/data-apis/array-api/issues/188. Disallowing it for higher dimensional arrays is probably fine, but it's unclear whether a library like array-api-strict should disallow it for 1-D arrays. The reason is that technically speaking, an array object that implements on the methods defined in the standard would allow iteration on 1-D arrays. This is because by default if __iter__ is not defined but __getitem__ is, Python defines iteration as a[0], a[1], etc.

Given how painful this can be for upstream code, I wonder if we should make it explicit in the standard that iteration is defined for 1-D arrays.

A possible counterargument is that the new unstack function can be used to iterate on an array of any dimension. unstack(x) is the same as iter(x) in the NumPy sense of iteration (it iterates the elements if x is 1-dimensional and along the first axis if it is n-dimensional).

asmeurer avatar Jul 01 '24 19:07 asmeurer