itemgetter with default arguments

Antoon Pardon antoon.pardon at vub.be
Tue May 8 04:29:10 EDT 2018


On 07-05-18 17:45, Peter Otten wrote:
> 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)

The problem with looking for such uses, is that I am working on a lot of
legacy code written in 2.2. It needed few adaptions to still work in 2.7
but I didn't adapt the code to make use of all the new features. But looking
at sort statements, it seems I have (the equivallent of) the following

itemgetter(2)
itemgetter(3)
itemgetter(4)
itemgetter(slice(0,-1))

-- 
Antoon Pardon.




More information about the Python-list mailing list