[Python-ideas] improvements to slicing

Andy Buckley andy at insectnation.org
Thu Oct 7 12:35:15 CEST 2010


On 06/10/10 22:35, Raymond Hettinger wrote:
> 
> On Oct 6, 2010, at 12:21 PM, Ron Adam wrote:
>> We don't need to change the current range function/generator to add inclusive or closed ranges.  Just add a closed_range() function to the itertools or math module.
>>
>>   [n for n in closed_range(-5, 5, 2)]  --> [-5, -3, -1, 1, 3, 5]
> 
> If I were a betting man, I would venture that you could post
> a recipe for closed_range(), publicize it on various mailing
> lists, mention it in talks, and find that it would almost never
> get used.
> 
> There's nothing wrong with the idea, but the YAGNI factor
> will be hard to overcome.  IMO, this would become cruft on 
> the same day it gets added to the library.

There are plenty of places in my code where I would find such a thing
useful, though... usually where I'm working with pre-determined integer
codes (one very specific use-case: elementary particle ID codes, which
are integers constructed from quantum number values) and it's simply
more elegant and intuitive to specify a range whose requested upper
bound is a valid code rather than valid_code+1.

IMHO, an extra keyword on range/xrange would allow to write nicer code
where applicable, without crufting up the library with whole extra
functions. Depends on what you consider more crufty, I suppose, but I
agree that ~no-one is going to find and import a new range function.
numpy.linspace uses "endpoint" as the name for such a keyword:
http://docs.scipy.org/doc/numpy/reference/generated/numpy.linspace.html#numpy.linspace
but again no-one wants to depend on numpy *just* to get that functionality!

So how about
  range(start, realend, endpoint=True)
  xrange(start, realend, endpoint=True)
with endpoint=False as default? No backward compatibility or performance
issues to my (admittedly inexpert) eye.

Andy




More information about the Python-ideas mailing list