BUG: Fix np.strings.slice if stop=None or start and stop >= len (#29944) #30059
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Python treats
slice(-1)differently fromslice(-1, None): The first is interpreted asslice(None, -1, None), while the second becomesslice(-1, None, None), according to the logic inslice_new.However,
np.strings.slicetreats these identically, as it cannot distinguish unset arguments from arguments set to None. This makes it impossible to get the last characters of each string, for example:This commit fixes that behavior:
It does this by adding a
stop=np._NoValuedefault argument tonp.strings.slice, which can be overridden withNone.This commit also adds test conditions to
numpy/_core/tests/test_strings.py::TestMethods::test_sliceto verify that the slicing behavior matches Python'sslice. Note that 4 newly added test conditions are commented out for now, as they cause errors with the "T" dtype. To reproduce:This causes either a MemoryError or kills the process with code 251.
Allows commented test_slice conditions to be uncommented.