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

Tim Delaney timothy.c.delaney at gmail.com
Thu Jul 3 01:10:18 CEST 2014


On 3 July 2014 07:29, Stefano Borini <stefano.borini at ferrara.linux.it>
wrote:

> On Thu, Jul 03, 2014 at 06:12:30AM +1000, Tim Delaney wrote:
> > One option I don't see is to have a[b=1, c=2] be translated to
> > a.__getitem__((slice('b', 1, None), slice['c', 2, None)) automatically.
>
> it would be weird, since it's not technically a slice, but it would work.
> I personally think that piggybacking on the slice would appear hackish.
> One could eventually think to have a keyword() object similar to slice(),
> but then it's basically a single item dictionary (Strategy 1) with a fancy
> name.


I really do think that a[b=c, d=e] should just be syntax sugar for a['b':c,
'd':e]. It's simple to explain, and gives the greatest backwards
compatibility. In particular, libraries that already abused slices in this
way will just continue to work with the new syntax.

I'd maybe thought a subclass of slice, with .key (= .start) and and .value
(= .stop) variables would work, but slice isn't subclassable so it would be
a bit more difficult. That would also be backwards-compatible with existing
__getitem__ that used slice, but would preclude people calling that
__getitem__ with slice syntax, which I personally don't think is
desireable. Instead, maybe recommend something like:

ordereddict = OrderedDictLiteral()  # using the definition from previous
email

class GetItemByName(object):
    def __getitem__(self, t):
        # convert the parameters to a dictionary
        d = ordereddict[t]
        return d['name']

Hmm - here's an anonymous named tuple "literal" as another example:

class AnonymousNamedTuple(object):
    def __getitem__(self, t):
        d = ordereddict[t]
        t = collections.namedtuple('_', d)
        return t(*d.values())

namedtuple = AnonymousNamedTuple()
print(namedtuple[a='b', c=1])  # _(a='b', c=1)

As you can see, I'm in favour of keeping the order of the keyword arguments
to the index - losing it would prevent things like the above.

Tim Delaney
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20140703/db8fccb3/attachment.html>


More information about the Python-ideas mailing list