Open 3b61c6b8-ac64-443b-8796-2aa06c5e8465 opened 3 years ago
It would be nice if there were a way to get a string representation of a slice object in extended indexing syntax, e.g.
>>> myslice = slice(None, None, 2)
>>> print(myslice)
'::2'
One motivating use-case is in descriptive error messages, e.g.
TypeError(f"Can't slice {myobj}, try list({myobj})[{myslice}]")
In this case, it is much more natural for myslice
to use the extended indexing syntax than the slice str/repr.
Perhaps this could be done via str, or if that is too big a change, maybe via format e.g. f"{myslice:asidx}"
It's simple enough to write a conversion function, but this feels like a feature that would fit best upstream. I searched the issue tracker, PRs on GitHub, and the Python documentation and didn't see any related issues/PRs/articles.
What you are or should be asking for is an alternate string representation method, perhaps called 'colon', so that for instance myslice.colon() == '::2'
The function could take an optional length (as with .indices, but optional) to produce the same numbers as .indices.
myslice.colon(8) == '0:8:2' slice(0, -1, 3).colon(14) == '0:13:3'
I suspect that something like this has been asked before. I suggest you post to python-ideas list to see if there is any support and any better idea for the name.
Note: these values reflect the state of the issue at the time it was migrated and might not reflect the current state.
Show more details
GitHub fields: ```python assignee = None closed_at = None created_at =
labels = ['interpreter-core', 'type-feature', '3.10']
title = 'A string representation of slice objects with colon syntax'
updated_at =
user = 'https://github.com/rossbar'
```
bugs.python.org fields:
```python
activity =
actor = 'terry.reedy'
assignee = 'none'
closed = False
closed_date = None
closer = None
components = ['Interpreter Core']
creation =
creator = 'rossbar'
dependencies = []
files = []
hgrepos = []
issue_num = 42352
keywords = []
message_count = 2.0
messages = ['380921', '381516']
nosy_count = 2.0
nosy_names = ['terry.reedy', 'rossbar']
pr_nums = []
priority = 'normal'
resolution = None
stage = 'test needed'
status = 'open'
superseder = None
type = 'enhancement'
url = 'https://bugs.python.org/issue42352'
versions = ['Python 3.10']
```