[Python-ideas] str(slice(10)) should return "slice(10)"

Steven D'Aprano steve at pearwood.info
Sat Nov 12 04:26:26 EST 2016


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

versus:

    slice(1, None)  # 14 characters
    slice(None, 1, None)  # 20 characters




-- 
Steve


More information about the Python-ideas mailing list