Skip to content

Adding an empty range() to an empty slice throws "Cannot cast ufunc 'add' output ..." #14317

@fj128

Description

@fj128

If we use an ndarray with a non-default dtype, take an empty slice and attempt to add an empty range to it:

Reproducing code example:

import numpy as np
v = np.zeros(5, dtype=np.int32)
v[0 : 0] += range(0)

Error message:

Exception has occurred: UFuncTypeError
Cannot cast ufunc 'add' output from dtype('float64') to dtype('int32') with casting rule 'same_kind'

Non-empty slice and range works obviously, assignment instead of += works, using default dtype works, np.arange works.

I checked performance and np.arange seems to be about a hundred times faster for any reasonably sized arrays (up to and including 10 million elements where range version becomes unbearably slow) anyways, so everyone should use that. It's still faster even for very small arrays.

But the error is pretty confusing, especially since as you can imagine zero-length slices arise in pretty confusing corner cases to begin with.

Also, it would be nice to have numpy.xarange or something, or mention that even arange is way faster than range in the documentation.

Numpy/Python version information:

1.17.0 3.7.4 (tags/v3.7.4:e09359112e, Jul 8 2019, 19:29:22) [MSC v.1916 32 bit (Intel)]

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions