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

Tim Delaney timothy.c.delaney at gmail.com
Wed Jul 2 22:12:30 CEST 2014


On 2 July 2014 08:36, Stefano Borini <stefano.borini at ferrara.linux.it>
wrote:

> Dear all,
>
> after the first mailing list feedback, and further private discussion with
> Joseph Martinot-Lagarde, I drafted a first iteration of a PEP for keyword
> arguments in indexing. The document is available here.
>
> https://github.com/stefanoborini/pep-keyword/blob/master/PEP-XXX.txt
>
> The document is not in final form when it comes to specifications. In
> fact, it requires additional discussion about the best strategy to achieve
> the desired result. Particular attention has been devoted to present
> alternative implementation strategies, their pros and cons. I will examine
> all feedback tomorrow morning European time (in approx 10 hrs), and apply
> any pull requests or comments you may have.
>
> When the specification is finalized, or this community suggests that the
> PEP is in a form suitable for official submission despite potential open
> issues, I will submit it to the editor panel for further discussion, and
> deploy an actual implementation according to the agreed specification for a
> working test run.
>
> I apologize for potential mistakes in the PEP drafting and submission
> process, as this is my first PEP.
>

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.
That completely takes care of backwards compatibility in __getitem__ (no
change at all), and also deals with your issue with abusing slice objects:

a[K=1:10:2] -> a.__getitem__(slice('K', slice(1, 10, 2)))

And using that we can have an ordered dict "literal"

class OrderedDictLiteral(object):
    def __getitem__(self, t):
        try:
            i = iter(t)
        except TypeError:
            i = (t,)

        return collections.OrderedDict((s.start, s.stop) for s in i)

odict = OrderedDictLiteral()

o = odict[a=1, b='c']
print(o)  # prints OrderedDict([('a', 1), ('b', 'c')])

On a related note, if we combined this with the idea that kwargs should be
constructed using the type of the passed dict (i.e. if you pass an
OrderedDict as **kwargs you get a new OrderedDict in the function) we could
do:

kw = OrderedDictLiteral()

def f(**kw):
    print(kw)

f('a', 'b', **kw[c='d', e=2])

always resulting in:

{'c': 'd', 'e': 2}

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


More information about the Python-ideas mailing list