[Python-ideas] Why don't CPython strings implement slicing using a view?

Terry Reedy tjreedy at udel.edu
Thu May 7 08:10:46 CEST 2015


On 5/6/2015 10:05 PM, Neil Girdhar wrote:
> Since strings are constant, wouldn't it be much faster to implement
> string slices as a view of other strings?
>
> For clarity, I'm talking about CPython.  I'm not talking about anything
> the user sees.  The string views would still look like regular str
> instances to the user.

The idea has been discussed and rejected.  See pydev thread 'The "lazy 
strings" patch", Oct 2006, for one example.

I think the best solution is a separate Seqview class.  On the thread 
above, Josiah Carlson pointed out that he had made such a class that 
worked with multiple Python versions *and* with any sequence class.  The 
only computation involved is addition of start values to indexes when 
accessing the underlying object, and that is not specific to strings. 
There might be something on PyPI already, but PyPI cannot search for 
compounds such as "string view" (or "lazy string").

The three dict view classes are, obviouly, separate classes.  They 
happen to be created with dict methods.  But that is partly for 
historical reasons -- the methods already existed  but returned lists in 
2.x.  The views were only a change in the output class (and the removal 
of arbitrary order).  The API could have been dict_keys(somedict), with 
'dict_keys' a builtin name.  So there is nothing actually wrong with 
Seqview(seq, start, stop, step=1).

-- 
Terry Jan Reedy



More information about the Python-ideas mailing list