Thoughts on PEP284

Alex Martelli aleax at aleax.it
Tue Sep 23 06:22:50 EDT 2003


Daniel Dittmar wrote:

> Stephen Horne wrote:
>>   for i in int [0:10:2] :
>>     ...
>>
>> that is, allow the 'int' type object to be sliced, and return an
>> iterator as the result - not just for the for loop, but generally
>> (though optimising the 'for' loop usage to avoid physically creating
>> the iterator might be a good idea).
> 
> Adding operators to types is always problematic because it defeats
> Pythons's runtime checking. Assuming that integer slicing would be added
> to Python, methods that would expect a list of integers would suddenly
> also work with integers. In most cases, they would not work correctly, but
> you wouldn't get a meaningful exception.

Careful: in Stephen's proposal, slicing would NOT work on *INTEGERS* --
rather, it would work on the *INT TYPE ITSELF*, which is a very, very
different issue.  "Methods that would expect a list of integers", ONLY
do slicing on that list, AND get mistakenly passed the type object
'int' itself -- would work just perfectly, as if they had been passed
"a list of all non-negative integers" or xrange(sys.maxint+1).


>> Also, one extra feature is that the loop can be infinite (which range
>> and xrange cannot achieve)...
>>
>>   for i in int [0:] :

No way, Jose -- now THAT would break things (in admittedly rare
cases -- a method expecting a list and NOT providing an upper bound
in the slicing).  I'd vote for this to be like int[0:sys.maxint+1]
(i.e., last item returned is sys.maxint).

>>     ...
>>     if condition : break
>>     ...
> 
> I'm sure that you can think of a generator function that does exactly the
> same.

Right, that's pretty trivial, and itertools.count() already does it anyway.


What Stephen's proposal lacks is rigorous specs of what happens for all
possible slices -- e.g int[0:-3] isn't immediately intuitive, IMHO;-).


Alex





More information about the Python-list mailing list