[Python-ideas] keyword-only args in __getitem__

Terry Reedy tjreedy at udel.edu
Sun Apr 13 00:30:47 CEST 2014


On 4/12/2014 3:28 PM, Joseph Martinot-Lagarde wrote:
> I propose to allow to define keyword-only arguments for __getitem__.
>
> 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

The problem with this is, as you note below, that everything between [ 
and ] is turned into a single object passed on to __getitem__. That 
includes slice notation I:J:I, which is currently only valid in this 
context. Syntactically, collection indexing is quite different from 
function calling. (Python could have been defined so that they were the 
same.) I think it would be better if the key were syntactically 
separated from a default, say with ;.
   value = lst[3; 0]

I believe any proposal along this line would make dict.getitem obsolete, 
and eliminate any call for list.getitem.

> Default value is not the only use case. One could for example define a
> subclass of list computing an interpolation if a float is given as a
> parameter instead of truncating it, and the keword argument would define
> which kind of interpolation (nearest, linear, spline...).

I think interp should be a method of the subclass.

> Or it could
> define if the value returned are in degrees or radians. (Yes, I have a
> scientific background.)

.setunit('degrees') with radians the default.

> I use something similar for a dictionary-like interface where the keys
> are strings and only numbers are stored. The second argument, if given,
> is the default:
>  >>> data["key", 0]
> It would be clearer to use:
>  >>> data["key", default=0]

I see data['key'; 0] as an in between compromise. The 0 is separated 
from the key but without the heavy 'default='.

> (Of course I could use a get method for this purpose, but bracket for
> indexing seems always more clear).

-- 
Terry Jan Reedy



More information about the Python-ideas mailing list