Antoon Pardon wrote: > On 05-05-18 09:33, Peter Otten wrote: >> I think you have established that there is no straight-forward way to >> write this as a lambda. But is adding a default to itemgetter the right >> conclusion? >> >> If there were an exception-catching decorator you could write >> >> f = catch(IndexError, "spam")(itemgetter(2)) > > I think your catch function would be a usefull addition, but I don't see > it solving this problem once we use itemgetter te get multiple entries.
Good catch() ;) The obvious way, expressing the n-tuple case in terms of the solution for scalars >>> f = lambda items: tuple(catch(IndexError, "spam")(itemgetter(i))(items) for i in (2, 1, 5)) >>> >>> f("abc") ('c', 'b', 'spam') is a bit too complex to inline -- and also inefficient. You'd be tempted to factor out the repetetive parts >>> f = lambda items, gets=[catch(IndexError, "spam")(itemgetter(i)) for i in (2, 1, 5)]: tuple(get(items) for get in gets) >>> f("abc") ('c', 'b', 'spam') and thus make it even less readable. That said -- grepping my code I'm a bit surprised to find only 17 itemgetter(0) 9 itemgetter(1) 1 itemgetter(1, 0) 1 itemgetter(*indices) Checking /usr/lib/python3/dist-packages it looks like the situation is similar. I conclude that the most useful addition to the operator module would be first = itemgetter(0) second = itemgetter(1) -- https://mail.python.org/mailman/listinfo/python-list