itemgetter with default arguments

Steven D'Aprano steve+comp.lang.python at pearwood.info
Fri May 4 22:26:44 EDT 2018


On Fri, 04 May 2018 15:27:02 +0200, Thomas Jollans wrote:

>>>> spamgetter = (lambda seq, i=2, fallback="spam":
> ...                  seq[i] if abs(i) < len(seq) or i == -len(seq) 
> ...                  else fallback)
>>>> spamgetter("abcd", i=-4)
> 'a'
>>>> spamgetter("abcd")
> 'c'
>>>> spamgetter("")
> 'spam'


Doh! Obvious in hindsight. Thanks.

And on my computer, it's only 125% slower than itemgetter.


> Making this work for sequences AND dict-like objects is more
> difficult...

Indeed. At least with dicts you can call .get(). I don't think it is 
necessary to have the one lambda handle both sequence and dict cases. 
Surely when calling it you know whether or not you are looking at a 
sequence or a mapping.



-- 
Steve




More information about the Python-list mailing list