[Python-Dev] Bad interaction of __index__ and sequence repeat

Nick Coghlan ncoghlan at iinet.net.au
Sat Jul 29 16:19:27 CEST 2006


Nick Coghlan wrote:
>   The other benefit is that the logic to downconvert to Py_ssize_t that 
> was formerly invoked by long's __index__ method is now instead invoked 
> by PyNumber_Index and PyNumber_SliceIndex. This means that directly 
> calling an __index__() method allows large long results to be passed 
> through unaffected, but calling the indexing operator will raise 
> IndexError if the long is outside the memory address space:
> 
>   (2 ** 100).__index__() == (2**100)  # This works
>   operator.index(2**100)              # This raises IndexError
> 
> The patch includes additions to test_index.py to cover these limit 
> cases, as well as the necessary updates to the C API and operator module 
> documentation.

I forgot to mention the main benefit of this: when working with a 
pseudo-sequence rather than a concrete one, __index__() can be used directly 
to ensure you are working with integral data types while still allowing access 
to the full range of representable integer values.

operator.index is available for when what you have really is a concrete data 
set that is limited to the memory capacity of a single machine, and 
operator.sliceindex for when you want to clamp at the memory address space 
limits rather than raising an exception.

Cheers,
Nick.

-- 
Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia
---------------------------------------------------------------
             http://www.boredomandlaziness.org


More information about the Python-Dev mailing list