itemgetter with default arguments

Ian Kelly ian.g.kelly at gmail.com
Fri May 4 11:17:14 EDT 2018


On Fri, May 4, 2018 at 7:01 AM, Steven D'Aprano
<steve+comp.lang.python at pearwood.info> wrote:
> Here are the specifications:
>
> * you must use lambda, not def;

Why? This seems like an arbitrary constraint.

> * the lambda must take a single function, the sequence you want to
>   extract an item from;
>
> * you can hard-code the index in the body of the lambda;
>
> * you can hard-code the default value in the body of the lambda;
>
> * if sequence[index] exists, return that value;
>
> * otherwise return the default value;
>
> * it should support both positive and negative indices.
>
> Example: given an index of 2 and a default of "spam":
>
>     (lambda seq: ... )("abcd") returns "c"
>
>     (lambda seq: ... )("") returns "spam"

def itemgetter2(*items, default):
    return lambda seq: tuple(get_default(seq, item, default) for item in items)

def get_default(seq, item, default):
    try:
        return seq[item]
    except (IndexError, KeyError):
        return default

py> f = itemgetter2(1, 6, default="spam")
py> f("Hello World!")
('e', 'W')
py> f("Hello!")
('e', 'spam')



More information about the Python-list mailing list