[Python-ideas] keyword-only args in __getitem__

Chris Angelico rosuav at gmail.com
Sun Apr 13 02:45:22 CEST 2014


On Sun, Apr 13, 2014 at 5:28 AM, Joseph Martinot-Lagarde
<joseph.martinot-lagarde at m4x.org> wrote:
> The main use case is to be able to set a default value for indexing. I
> though about it after reading PEP 463 (Exception-catching expressions), this
> would be an alternative for one of the problem this PEP is trying to solve.
> Compare these solutions:
>>>> lst = [1, 2, 3]
>>>> value = lst[3]
> Traceback (most recent call last):
>   File "<stdin>", line 1, in <module>
> IndexError: list index out of range
>>>> try:  # Python
> ....     value = lst[3]
> .... except IndexError:
> ....     value = 0
>>>> value = lst[3] except IndexError: 0  # PEP 463
>>>> value = lst[3, default=0]  # My proposal

An interesting idea, but that looks far too much like a function call.
Square brackets and then more and more a function call inside... may
fail the grit test.

Part of the point of except expressions was that the implementation of
__getitem__ wouldn't need to have two branches in it. Currently, you
need to write __getitem__ (which raises an exception on finding a
problem) plus something else, eg get(), which returns a default
instead. By your proposal, both branches would go inside __getitem__,
which means they could share code; but there still need to be two
branches. That's two branches that need to be written, tested, etc,
and if the author hasn't thought to handle default=, there's no way to
get that functionality, same as if there's no get() method. And just
as with the get method, there'll be an ad-hoc and fairly arbitrary
puddle of names (some will go "default=", others will say that's way
too long and go "def=", except that that's a keyword so they'll use
"dflt=" or something...), unless there's a strong force pushing people
to one consistent name. Terry's suggestion solves that part of it, but
also restricts the feature to just default values; with a more general
keyword argument system, it would make sense to also use this with
__setitem__ and __delitem__, and I'm not sure how "default value"
should be interpreted there. Which is better is, of course, a matter
of opinion! :)

ChrisA


More information about the Python-ideas mailing list