[Python-ideas] keyword-only args in __getitem__
Ron Adam
ron3200 at gmail.com
Sun Apr 13 19:21:28 CEST 2014
On 04/12/2014 06:30 PM, Terry Reedy wrote:
> 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__.
The comma in slice notation does support passing multiple objects to get
item. It's used in numpy for multidimensional lookups. I believe there is
interest for adding that feature to python, so it may cause an issue with
those proposals if the comma is used.
But it seems to me a better way to do this may be with default method that
returns a view or wrapped object that supplies a default rather than raise
an index or key error.
lst.default_view(0)[3]
Generally you won't use different defaults with the same object that often,
so it makes sense to set it early, and then not to have to do anything
special in other places the object is used.
Cheers,
Ron
More information about the Python-ideas
mailing list