[Python-ideas] Accepting keyword arguments for __getitem__
Chris Angelico
rosuav at gmail.com
Mon Jun 23 14:24:53 CEST 2014
On Mon, Jun 23, 2014 at 10:06 PM, Stefano Borini
<stefano.borini at ferrara.linux.it> wrote:
> 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):
> ... print(y)
> ...
>>>> a=A()
>>>> a[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}.
The obvious way to accept that would be to support keyword arguments,
and then it begins looking very much like a call. Can you alter your
notation very slightly to become LDA(Z=5) instead? Then you can accept
that with your class thus:
class A:
def __call__(self, Z):
print(Z)
Or you can accept it generically with keyword arg collection:
class A:
def __call__(self, **kw):
print(kw)
>>> a=A()
>>> a(Z=3)
{'Z': 3}
Requires a small change to notation, but no changes to Python, ergo it
can be done without waiting for a new release!
ChrisA
More information about the Python-ideas
mailing list