[Python-ideas] keyword-only args in __getitem__

Joseph Martinot-Lagarde joseph.martinot-lagarde at m4x.org
Sun Apr 13 22:21:14 CEST 2014


Le 13/04/2014 19:21, Ron Adam a écrit :
>
>
> 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.

It may be true for lists as they are supposed to hold objects of the 
same kind. But for dictionnaries, you may want to have different 
defaults for each key. For example a dictionary containing the keys 
'START', 'STOP' and 'STEP' would have something like 0, None and 1 as 
defaults.

>
>
> Cheers,
>     Ron
>
> _______________________________________________
> Python-ideas mailing list
> Python-ideas at python.org
> https://mail.python.org/mailman/listinfo/python-ideas
> Code of Conduct: http://python.org/psf/codeofconduct/
>


---
Ce courrier électronique ne contient aucun virus ou logiciel malveillant parce que la protection avast! Antivirus est active.
http://www.avast.com




More information about the Python-ideas mailing list