Home
Reading
Searching
Subscribe
Sponsors
Statistics
Posting
Contact
Spam
Lists
Links
About
Hosting
Filtering
Features Download
Marketing
Archives
FAQ
Blog
 
Gmane
From: Joseph Martinot-Lagarde <joseph.martinot-lagarde-oWGTIYur0i8 <at> public.gmane.org>
Subject: keyword-only args in __getitem__
Newsgroups: gmane.comp.python.ideas
Date: Saturday 12th April 2014 19:28:40 UTC (over 3 years ago)
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 "", line 1, in 
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

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...). Or it could 
define if the value returned are in degrees or radians. (Yes, I have a 
scientific background.)

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]
(Of course I could use a get method for this purpose, but bracket for 
indexing seems always more clear).


The keyword would be keywords-only because right now when many arguments 
are passed to __getitem__, they are grouped in a tuple and this tuple is 
passed to __getitem__ as a unique argument. Also it is more clear: 
ordered arguments are the indexes, keyword arguments are the options.


To be perfectly honest I don't think that this proposal is that great, 
it's main selling point is that a "default" keyword in indexing would be 
a good alternative for some of the problems raised in PEP 463.

Joseph ML

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


_______________________________________________
Python-ideas mailing list
[email protected]
https://mail.python.org/mailman/listinfo/python-ideas
Code of Conduct: http://python.org/psf/codeofconduct/
 
CD: 3ms