Skip to content

Conversation

@benbovy
Copy link
Member

@benbovy benbovy commented Jun 30, 2025

# TODO: support reverse transform (i.e., start > stop)?
assert sl.start < sl.stop

new_size = (sl.stop - sl.start) // sl.step
Copy link
Contributor

@dcherian dcherian Jun 30, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

One trick I have learned is to use range objects to outsource this logic to CPython (e.g. #7586)

So you could do:

newrange = range(self.size)[sl]
start = newrange.start
step = newrange.step or 1
size = len(newrange)

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nice trick, this also allows supporting reverse indexing without additional effort.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actually, I remember the real API is slice.indices(size) so an alternative is :

        start, stop, step = slicer.indices(self.size)
        size = len(range(start, stop, step))

I think you still need to construct the range object to get the right size so not much difference

This also enables support for reverse slicing (added tests)
@dcherian dcherian merged commit f778624 into pydata:main Jul 1, 2025
31 of 33 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

slicing DataArray with RangeIndex coordinate can put coordinate in inconsistent state

2 participants