[Python-Dev] itertools addition: getitem()
walter at livinglogic.de
Sun Jul 8 15:30:37 CEST 2007
Guido van Rossum wrote:
> On 7/8/07, Georg Brandl <g.brandl at gmx.net> wrote:
>> Guido van Rossum schrieb:
>>> How important is it to have the default in this API? __getitem__()
>>> doesn't have a default; instead, there's a separate API get() that
>>> provides a default (and I find defaulting to None more manageable than
>>> the "_default = object()" pattern).
Of course it isn't implemented this way in the C version.
>> getattr() has a default too, while __getattr__ hasn't...
> Fair enough.
> 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:
foo = getitem(iterable, 0)
Here is a use case from one of my "import XML into the database" scripts:
compid = getitem(root[ns.Company_company_id], 0, None)
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.
More information about the Python-Dev