[Python-Dev] [NPERS] Re: a feature i'd like to see in python #2: indexing of match objects

Josiah Carlson jcarlson at uci.edu
Wed Dec 6 21:29:56 CET 2006


Alastair Houghton <alastair at alastairs-place.net> wrote:
> On 5 Dec 2006, at 15:51, Fredrik Lundh wrote:
> > Alastair Houghton wrote:
> >> or
> >>
> >>    m[3:4]
> >>
> >> fail to do what they expect.
> >
> > the problem with slicing is that people may 1) expect a slice to  
> > return
> > a new object *of the same type*
> 
> What I would have expected is that it supported a similar set of  
> sequence methods---that is, that it returned something with a similar  
> signature.  I don't see why code would care about it being the exact  
> same type.

The problem is that either we return a list (easy), or we return
something that is basically another match object (not quite so easy). 
Either way, we would be confusing one set of users or another.  By not
including slicing functionality by default, we sidestep the confusion.


> Anyway, clearly what people will expect here (talking about the match  
> object API) is that m[3:4] would give them a list (or some equivalent  
> sequence object) containing groups 3 and 4.  Why do you think someone  
> would expect a match object?

Because that is what all other slicing operations in base Python do. 
List, tuple, string, unicode, array, buffer, ...  Even extension writers
preserve the functionality with Numeric, etc.  When you slice a sequence,
you get back a slice of that sequence, of the same type you started out
with.


> > I prefer the "If the implementation is easy to explain, it may be a  
> > good idea." design principle over "can of worms" design principle.
> 
> As someone who is primarily a *user* of Python, I prefer the idea  
> that sequence objects should operate consistently to the idea that  
> there might be some that don't.  By which I mean that anything that  
> supports indexing using integer values should ideally support slicing  
> (including things like [::-1]).

You are being inconsistant.  You want list, tuple, etc. to be consistant,
but you don't want match objects to be consistant.  Sorry, but that is
silly. Better to not support slices than to confuse the hell out of
people by returning a tuple or list from a match slicing.

If people want slicing, they can do list(m)[x:y].  If their matches are
of sufficient size where that is a "slow" operation, then they can do 
[m[i] for i in xrange(x,y)] .

 - Josiah



More information about the Python-Dev mailing list