beginning index for generators

Peter Otten __peter__ at web.de
Sun Oct 17 04:46:39 EDT 2004


Andrew Dalke wrote:

> Peter Otten wrote:
>> def irange(start, stop, step):
> 
> Isn't that xrange?

No. That's what I would like xrange() to be. It has no artificial (if
generous) sys.maxint limit and can be open-ended, i. e. comprises the
itertools.count() functionality extended for step != 1.

>> def islice(iterable, start, step, stop):
> 
> And that's itertools.islice?

No, but it _calls_ itertool.islice() as you may have noted :-)
Its raison d'être is that it allows to pass the start, stop, and step
attributes of a slice object without looking into the special cases.
itertools.islice() works with different signatures instead of None default
values. When called with three parameters, only 'stop' may be None. Slice
literals cannot be that strict because they may have a negative step, in
which case start values of None and 0 have a different meaning.

I had all checks for special cases in the iterate class first and factored
them out as an afterthought because they made it harder to see how simple
'iterate' really was.
 
>> class iterate(object):
>>     def __init__(self, iterable):
>>         self.iterable = iterable
>>     def __getitem__(self, s):
>>         if not isinstance(s, slice):
>>             raise ValueError("supports only slices")
>>         start, stop, step = s.start, s.stop, s.step
>>         if hasattr(self.iterable, "__getitem__"):
> 
> And doesn't that test fail for dictionaries?

Yes, unfortunately. Discriminating between dictionaries and lists has been
deliberately left out. Is there a recommended way to do it? Looking for a
'keys' attribute maybe? Anyway, as long as something like iterate is not
built into the iterator protocol, it is up to the programmer to decide
whether it can help or do harm. Dictionaries may be wrapped somewhere up
the callstack:

>>> hasattr(iter({}), "__getitem__")
False

Peter





More information about the Python-list mailing list