itemgetter with default arguments

Chris Angelico rosuav at gmail.com
Fri May 4 11:46:04 EDT 2018


On Sat, May 5, 2018 at 1:17 AM, Ian Kelly <ian.g.kelly at gmail.com> wrote:
> 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.
>
> 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')

PEP 463 wants to say hello.

ChrisA



More information about the Python-list mailing list