Another approach could be too simply pass the labelled indices in a dict as a third/fourth positional argument.So for indexingb = arr[1, 2, a=3, b=4]Instead of__getitem__(self, (1, 2), a=3, b=4)Just do__getitem__(self, (1, 2), {'a': 3, 'b': 4})
Go through the exercise. I have -- I've written Python 2 code that
needed to handle-keyword only arguments, and this was the only way to do
so.
The "only one parameter, which may receive a keyobject" design will
have us writing code something like this:
# I want this: def __getitem__(self, item, * a, b, c, d=0)
# but have to write this:
def def __getitem__(self, item):
# Determine whether we got any keyword arguments.
if isinstance(item, keyobject):
keys = item
item = ()
elif isinstance(item, tuple):
# Assuming that all keyword args are at the end;
# if there could be more than one keyobject, or if
# they could be anywhere in the tuple, this becomes
# even more complex. I don't even want to think
# about that case.
if item and isinstance(item[-1], keyobject):
keys = item[-1]
item = item[:-1]
else:
keys = keyobject()
# Now extract the parameters from the key object.
if 'a' in keys:
a = keys.pop('a')
else:
raise TypeError('missing keyword argument "a"')
# same for b and c
d = keys.pop('d', 0)
# Check for unexpected keywords.
if keys:
raise TypeError('unexpected keyword')
(Any bugs in the above are not intentional.) And now finally we can
actually use the keyword parameters and write the method.
Here's how it goes. First we writeclass D:
@wibble
def __setitem__(self, val, u, v, x, y):
pass # Or do something.Next, we define wibble. It will be a SIGNATURE CHANGING ADAPTER. Those who know how to make decorators will, I hope, have little difficulty in defining wibble to do what is required. For this exercise, assume that k.argv = (1, 2), and k.kwargs = dict(x=3, y=4).