[Python-Dev] itertools addition: getitem()

Walter Dörwald walter at livinglogic.de
Sun Jul 8 22:00:30 CEST 2007

Guido van Rossum wrote:

> On 7/8/07, Walter Dörwald <walter at livinglogic.de> wrote:
> [quoting Guido]
>> > But I still want to hear of a practical use case for the default here.
>> In most cases
>>     foo = getitem(iterable, 0, None)
>>     if foo is not None:
>>        ...
>> is simpler than:
>>     try:
>>        foo = getitem(iterable, 0)
>>     except IndexError:
>>        pass
>>     else:
>>        ...
>> Here is a use case from one of my "import XML into the database" scripts:
>>     compid = getitem(root[ns.Company_company_id], 0, None)
>>     if compid:
>>        compid = int(compid)
>> The expression root[ns.company_id] returns an iterator that produces all
>> children of the root node that are of the element type company_id. If
>> there is a company_id its content will be turned into an int, if not
>> None will be used.
> Ahem. I hope you have a better use case for getitem() than that
> (regardless of the default issue). I find it clearer to write that as
> try:
>  compid = root[ns.company_id].next()
> except StopIteration:
>  compid = None
> else:
>  compid = int(compid)
> While this is more lines, it doesn't require one to know about
> getitem() on an iterator. This is the same reason why setdefault() was
> a mistake -- it's too obscure to invent a compact spelling for it
> since the compact spelling has to be learned or looked up.

Well I have used (a Python version of) this getitem() function to 
implement a library that can match a CSS3 expression against an XML 
tree. For implementing the nth-child(), nth-last-child(), nth-of-type() 
and nth-last-of-type() pseudo classes (see 
http://www.w3.org/TR/css3-selectors/#structural-pseudos) getitem() was 
very useful.


More information about the Python-Dev mailing list