<p dir="ltr">On May 5, 2015 5:46 AM, "Cecil Westerhof" <<a href="mailto:Cecil@decebal.nl">Cecil@decebal.nl</a>> wrote:<br>
><br>
> Op Tuesday 5 May 2015 12:41 CEST schreef Steven D'Aprano:<br>
><br>
> > # Untested.<br>
> > def get_message_slice(message_filename, start=0, end=None, step=1):<br>
> > real_file = expanduser(message_filename)<br>
> > messages = []<br>
> > # FIXME: I assume this is expensive. Can we avoid it?<br>
> > nr_of_messages = get_nr_of_messages(real_file)<br>
><br>
> If I want to give the possibility to use negative values also, I need<br>
> the value.</p>
<p dir="ltr">You could make this call only if one of the boundaries is actually negative. Then callers that provide positive values don't need to pay the cost of that case.</p>
<p dir="ltr">Alternatively, consider that it's common for slices of iterators to disallow negative indices altogether, and question whether you really need that.</p>
<p dir="ltr">> > the_slice = slice(start, end, step)<br>
> > # Calculate the indexes in the given slice, e.g.<br>
> > # start=1, stop=7, step=2 gives [1,3,5].<br>
> > indices = range(*(the_slice.indices(nr_of_messages)))<br>
> > with open(real_file, 'r') as f:<br>
> > for i, message in enumerate(f):<br>
> > if i in indices:<br>
> > messages.append(message)<br>
> > return messages</p>
<p dir="ltr">I approve of using slice.indices instead of calculating the indices manually, but otherwise, the islice approach feels cleaner to me. This reads like a reimplementation of that.</p>