On 2/09/20 3:44 am, Steven D'Aprano wrote:
(9) Keyword-only subscripts are permitted:

     obj[spam=1, eggs=2]
     # calls type(obj).__getitem__(spam=1, eggs=2)

     del obj[spam=1, eggs=2]
     # calls type(obj).__delitem__(spam=1, eggs=2)

An alternative is to pass an empty tuple as the index when there
are no positional args. That would make the following less of a
special case:

but note that the setter is awkward since the signature requires the
first parameter:

     obj[spam=1, eggs=2] = value
     # wants to call type(obj).__setitem__(???, value, spam=1, eggs=2)

Gotchas
-------

     def __getitem__(self, index, direction='north')

if the caller uses this:

     obj[0, 'south']

they will probably be surprised by the method call:
>
     obj.__getitem__((0, 'south'), direction='north')

Solution: best practice suggests that keyword subscripts should be
flagged as keyword-only when possible:

     def __getitem__(self, index, *, direction='north')

Note that this will only help if the user looks at and takes careful
notice of the signature of the __getitem__ method -- it won't actually
prevent them from attempting to do obj[0, 'south'] and won't affect
the result if they do.

A better best practice would be to use a decorator such as the one
I posted earlier to convert the packed positional args into real
ones. Then they will get the expected result in most cases.

--
Greg
_______________________________________________
Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-le...@python.org
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at 
https://mail.python.org/archives/list/python-ideas@python.org/message/N7FXYFGIP2SAZ6BAGAI7LKCAHWC7SRQC/
Code of Conduct: http://python.org/psf/codeofconduct/

Reply via email to