[Python-ideas] Accepting keyword arguments for __getitem__
Terry Reedy
tjreedy at udel.edu
Mon Jun 23 19:11:29 CEST 2014
On 6/23/2014 8:06 AM, Stefano Borini wrote:
> Dear all,
>
> At work we use a notation like LDA[Z=5] to define a specific level
> of accuracy for our evaluation. This notation is used
> just for textual labels, but it would be nice if it actually worked
> at the scripting level, which led me to think to the following:
> at the moment, we have the following
>
>>>> class A:
> ... def __getitem__(self, y):
This actually says that y can be passed by position or name ;-)
> ... print(y)
> ...
>>>> a=A()
>>>> a[2]
> 2
>>> a.__getitem__(y=2)
2
>>>> a[2,3]
> (2, 3)
>>>> a[1:3]
> slice(1, 3, None)
>>>> a[1:3, 4]
> (slice(1, 3, None), 4)
>>>>
>
> I would propose to add the possibility for a[Z=3], where y would then be a
> dictionary {"Z": 3}. In the case of a[1:3, 4, Z=3, R=5], the value of y would
> be a tuple containing (slice(1,3,None), 4, {"Z": 3}, {"R": 5}). This allows to
> preserve the ordering as specified (e.g. a[Z=3, R=4] vs a[R=4, Z=3]).
As others have pointed out, you are not actually asking that __getitem__
'accept keyword arguments'. Rather you are asking that "x=y" be seen as
an abbreviation for "{'x':y}" in a very rare usage in a particular
context to save 4 (admittedly awkward) keystrokes. The resulting
confusion is not worth it. Saving 4 of 7 might seem worth it, but it
real cases, like "precision=4" versus "{'precision':4}" the ratio is
lower. I also wonder whether you might sometimes us the same spec in
multiple subscriptings, so that you might define "p = {'precision': 4}"
once and use it multiple times.
In your introductory paragraph, you only specify one optional parameter
-- accuracy. So it is not clear why you do not just write a .get(self,
ob, accuaracy=default) method. If their are multiple options, make them
keyword only.
--
Terry Jan Reedy
More information about the Python-ideas
mailing list