On Fri, Jul 10, 2020, 12:44 Steven D'Aprano <steve@pearwood.info> wrote:
On Fri, Jul 10, 2020 at 02:48:31PM +0200, Alex Hall wrote:
I believe he was saying it would be weird if `d[1, 2]` called `d.__getitem__((1, 2))` but `d[1, 2, x=3]` called `d.__getitem__(1, 2, x=3)`. More generally, if `__getitem__` always receives a single positional argument now, it should probably stay that way for consistency.
Right -- I already said as much too :-)
I think Jonathan's K class is a red herring (except to the degree that it could be used for experimentation). For backwards compatibility, it would be difficult or impossible to support multiple positional arguments. But we could add keyword only args to subscripting (if there is a compelling need for them) easily.
Existing signatures would stay the same:
def __getitem__(self, item) def __setitem__(self, item, value)
but those who wanted keyword args could add them, with or without defaults:
def __getitem__(self, item, *, spam=None) def __setitem__(self, item, value, *, spam, eggs=None)
I trust the expected behaviour is obvious, but in case it's not:
myobj[1, 2, spam=3] # calls __getitem__((1, 2), spam=3)
myobj[1, 2, spam=3] = 999 # calls __setitem__((1, 2), 999, spam=3, eggs=None)
(And similarly for delitem of course.)
I must admit I like the look of this, but I don't know what I would use it for.
This would be EXTREMELY useful for xarray, which uses labelled dimensions. So you can index and slice based on dimension position, but also based on dimension name. It is currently very awkward to index or slice by dimension name, though (particularly for slicing).