I like this idea of giving `slice` a metaclass that defines a `.__getitem__()` allowing us to construct slices on the slice type itself.
FWIW, this is exactly what pandas.IndexSlice does. E.g., from http://pandas.pydata.org/pandas-docs/stable/advanced.html:
In : dfmi.loc[(slice('A1','A3'),slice(None), ['C1','C3']),:]
In : idx = pd.IndexSlice In : dfmi.loc[idx[:,:,['C1','C3']],idx[:,'foo']]
This is one of those nifty things that's buried in Pandas but not well documented. I'd rather spell the above simply as:
I like the change proposed to `str(slice(10))` also... and it would be way better if `slice[:10]` were actual "syntax." In fact, in that case it could even be the repr().
Note: Notwithstanding my scare quotes, Steven isn't actually asking for new syntax. "slice" is already a name, and names can already be followed by square brackets. He's just asking for a new method on a metaclass.
On Sat, Nov 12, 2016 at 1:26 AM, Steven D'Aprano firstname.lastname@example.org wrote:
On Thu, Oct 06, 2016 at 04:19:17PM -0700, Neil Girdhar wrote:
Currently str(slice(10)) returns "slice(None, 10, None)"
If the start and step are None, consider not emitting them. Similarly slice(None) is rendered slice(None, None, None).
When you're printing a lot of slices, it's a lot of extra noise.
I have an alternative suggestion. Wouldn't it be nice if slice objects looked something like the usual slice syntax?
If you think the answer is No, then you'll hate my suggestion :-)
Let's keep the current repr() of slice objects as they are, using the full function-call syntax complete with all three arguments show explicitly:
repr(slice(None, None, None)) => "slice(None, None, None)"
But let's make str() of a slice more suggestive of actual slicing, and as a bonus, make slices easier to create too.
str(slice(None, None, None)) => "slice[:]"
Let the slice type itself be sliceable, as an alternate constuctor:
slice[:] => returns slice(None) slice[start:] => returns slice(start, None) slice[:end] => returns slice(None, end) slice[start::step] => returns slice(start, None, step)
and so forth. (This probably would require changing the type of slice to a new metaclass.)
And then have str() return the compact slice syntax.
At worst, the compact slice syntax is one character longer than the optimal function syntax:
# proposed slice str() slice[:7] # 9 characters # proposed compact str() slice(7) # 8 characters # current str() slice(None, 7, None) # 20 characters
but it will be more compact more often:
slice[1:] # 9 characters
slice(1, None) # 14 characters slice(None, 1, None) # 20 characters
-- Steve _______________________________________________ Python-ideas mailing list Pythonemail@example.com https://mail.python.org/mailman/listinfo/python-ideas Code of Conduct: http://python.org/psf/codeofconduct/