[Python-Dev] itertools addition: getitem()
Guido van Rossum
guido at python.org
Sun Jul 8 16:49:45 CEST 2007
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.
--
--Guido van Rossum (home page: http://www.python.org/~guido/)
More information about the Python-Dev
mailing list