[Python-ideas] PEP pre-draft: Support for indexing with keyword arguments
Bruce Leban
bruce at leapyear.org
Sat Jul 5 05:16:59 CEST 2014
On Fri, Jul 4, 2014 at 11:10 AM, Stefano Borini <
stefano.borini at ferrara.linux.it> wrote:
> On Wed, Jul 02, 2014 at 12:36:48AM +0200, Stefano Borini wrote:
> > https://github.com/stefanoborini/pep-keyword/blob/master/PEP-XXX.txt
>
> Strategy 4: Strict dictionary
> -----------------------------
>
> This strategy accepts that __getitem__ is special in accepting only one
> object,
> and the nature of that object must be non-ambiguous in its specification
> of the
> axes: it can be either by order, or by name. As a result of this
> assumption,
> in presence of keyword arguments, the passed entity is a dictionary and all
> labels must be specified.
>
The result that "all labels must be specified" does not follow from that
assumption that the object must be unambiguous. Numbers are not valid
keyword names but are perfectly useful as index values. See below. Note
that I am not advocating for/against strategy 4, just commenting on it.
>
> C0. a[1]; a[1,2] -> idx = 1; idx=(1, 2)
> C1. a[Z=3] -> idx = {"Z": 3}
> C2. a[Z=3, R=4] -> idx = {"Z"=3, "R"=4}
> C3. a[1, Z=3] -> {0: 1, "Z": 3}
> C4. a[1, Z=3, R=4] -> {0: 1, "Z": 3, "R": 4}
C5. a[1, 2, Z=3] -> {0: 1, 1: 2, "Z": 3}
> C6. a[1, 2, Z=3, R=4] -> {0: 1, 1: 2, "Z": 3, "R": 4}
C7. a[1, Z=3, 2, R=4] -> raise SyntaxError
>
> Note that idx[0] would have the same value it would have in the normal
__getitem__ call while in all cases above idx[3] would raise an exception.
It would not be the case that a[1,2] and a[x=1,y=2] would be
interchangeable as they would for function calls. That would still have to
be handled by the __getitem__ function itself. But it's fairly easy to
write a function that does that:
def extract_indexes(idx, args):
# args is a list of tuples either (key, default) or (key,) if no default
result = []
for i, arg in zip(itertools.count(), args):
if i in idx and arg[0] in idx:
raise IndexError
result.append(idx[i] if i in idx else idx[arg[0]] if arg[0] in idx
else arg[1])
return result
This raises IndexError if a key value is specified both positionally and by
name or if a missing key value does not have a default. It should also (but
does not) raise IndexError when idx contains extra keys not listed in args.
It also doesn't support unnamed (positional only) indexes. Neither of those
is difficult to add.
--- Bruce
Learn how hackers think: http://j.mp/gruyere-security
https://www.linkedin.com/in/bruceleban
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20140704/6bda998a/attachment.html>
More information about the Python-ideas
mailing list