This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

classification
Title: A string representation of slice objects with colon syntax
Type: enhancement Stage: test needed
Components: Interpreter Core Versions: Python 3.10
process
Status: open Resolution:
Dependencies: Superseder:
Assigned To: Nosy List: rossbar, terry.reedy
Priority: normal Keywords:

Created on 2020-11-13 18:47 by rossbar, last changed 2022-04-11 14:59 by admin.

Messages (2)
msg380921 - (view) Author: Ross Barnowski (rossbar) Date: 2020-11-13 18:47
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.

xref: https://github.com/networkx/networkx/pull/4304
msg381516 - (view) Author: Terry J. Reedy (terry.reedy) * (Python committer) Date: 2020-11-21 01:37
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.
History
Date User Action Args
2022-04-11 14:59:38adminsetgithub: 86518
2020-11-21 01:37:45terry.reedysetnosy: + terry.reedy
messages: + msg381516

components: + Interpreter Core
stage: test needed
2020-11-13 18:47:56rossbarcreate