[issue4124] Patch for adding "default" to itemgetter and attrgetter

Raymond Hettinger report at bugs.python.org
Tue Feb 3 21:28:53 CET 2009


Raymond Hettinger <rhettinger at users.sourceforge.net> added the comment:

That makes sense.  You've found two object models that have optional
attributes and have had some need to extract them with a default.

My remaining concern is about adding complexity for functionality that
is not often needed.  It wouldn't be an issue if itemgetter() and
attrgetter() already had a simple signature, but they already allow
multiple arguments and IMO that doesn't mesh well with providing defaults.

FWIW, looking back at your use cases, it feels like the functional tools
have come together awkwardly.  It may be slower, but the following seems
easier to read, easier to write, and clearer about its intention:

  sum('tr' == getattr(node, 'name', '') for node in soup)
  max(getattr(art, 'time', 0) for art in articles)

In general, listcomps and genexps read better than equivalents using
lambda or a stack of builtin operators. And, lambda is dog slow.  So,
the following may be slower than the above code:

 len(filter(lambda n: n == "tr", map(attrgetter("name", ""), soup)))

_______________________________________
Python tracker <report at bugs.python.org>
<http://bugs.python.org/issue4124>
_______________________________________


More information about the Python-bugs-list mailing list