[Python-ideas] PEP pre-draft: Support for indexing with keyword arguments

drekin at gmail.com drekin at gmail.com
Fri Jul 4 11:29:34 CEST 2014


Just some ideas, not claiming they are good:

• As already stated in the thread and also in the PEP, there are two different classes of uses cases of indexing with keyword arguments: as a named index, and as an option contextual to the indexing. I think that the cases ask for different signatures. Even if I have a complex indexing scheme, the signature is (assumming Strategy 1 or 3):

def __getitem__(self, idx): …

However if I now want to add support for default value, I would do it like:

_Empty = object()
def __getitem__(self, idx, *, default=_Empty): …

That leads to the following strategies.

• Just for sake of completeness, maybe the easiest and also most powerful strategy would be just copying of behaviour of function call just with arguments going to __getitem__ instead of __call__ and allowing the syntax sugar for slices (which would raise the question whether to allow slice literals also in functin call or even in every expression).

This strategy has two serious problems:
    1. It is not backwards compatible with current mechanism of automatic packing of positional arguments.
    2. It is not clear how to intercorporate the additional parameter of __setitem__.

• This takes me to the following hybrid strategy. Both strategies 1 and 3 pack everything into one idx object whereas stratery 2 leaves key indices in separate kwargs parameter. The hybrid strategy takes as much as possible from function call strategy and generalizes strategies 1, 2, 3 at the same time.

The general signature looks like this:
def __getitem__(self, idx, *, key1, key2=default, **kwargs): …
During the call, every provided keyword argument with present corresponding parameter is put into that parameter. If there is **kwargs parameter then the remaining keyword arguments are put into kwargs and if not then they are somehow (strategy 1 or 3) packed into idx parameter.

Also the additional __setitem__ argument is just added as positional argument:
def __setitem__(self, idx, value, *, key1, key2=default, **kwargs): …


Regards, Drekin




More information about the Python-ideas mailing list