[Python-Dev] itertools addition: getitem()

Walter Dörwald walter at livinglogic.de
Mon Jul 9 21:23:40 CEST 2007


Raymond Hettinger wrote:

> From: "Guido van Rossum" <guido at python.org>
>> But doesn't the very same argument also apply against islice(), which
>> you just offered as an alternative?
> 
> Not really.  The use cases for islice() typically do not involve
> repeated slices of an iterator unless it is slicing off the front
> few elements on each pass.  In contrast, getitem() is all about
> grabbing something other than the frontmost element and seems
> to be intended for repeated calls on the same iterator. 

That wouldn't make sense as getitem() consumes the iterator! ;)

But seriously: perhaps the name getitem() is misleading? What about 
item() or pickitem()?

> And its
> support for negative indices seems somewhat weird in the
> context of general purpose iterators:  getitem(genprimes(), -1).

This does indeed make as much sense as sum(itertools.count()).

> I'll study Walter's use case but my instincts say that adding
> getitem() will do more harm than good.

Here's the function in use (somewhat invisibly, as it's used by the 
walknode() method). This gets the oldest news from Python's homepage:

 >>> from ll.xist import parsers, xfind
 >>> from ll.xist.ns import html
 >>> e = parsers.parseURL("http://www.python.org", tidy=True)
 >>> print e.walknode(html.h2 & xfind.hasclass("news"))[-1]
Google Adds Python Support to Google Calendar Developer's Guide


Get the first comment line from a python file:

 >>> getitem((line for line in open("Lib/codecs.py") if 
line.startswith("#")), 0)
'### Registry and builtin stateless codec functions\n'


Create a new unused identifier:

 >>> def candidates(base):
...     yield base
...     for suffix in count(2):
...         yield "%s%d" % (base, suffix)
...
 >>> usedids = set(("foo", "bar"))
 >>> getitem((i for i in candidates("foo") if i not in usedids), 0)
'foo2'

Servus,
    Walter



More information about the Python-Dev mailing list