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

C Anthony Risinger anthony at xtfx.me
Wed Jul 2 04:58:44 CEST 2014


On Jul 1, 2014 8:06 PM, "Chris Angelico" <rosuav at gmail.com> wrote:
>
> [...]
>
> For the OP's use-case, though, it would actually be possible to abuse
> slice notation. I don't remember this being mentioned, but it does
> preserve order; the cost is that all the "keywords" have to be defined
> as objects.
>
> class kw: pass # because object() doesn't have attributes
> def make_kw(names):
>     for i in names.split():
>         globals()[i] = obj = kw()
>         obj.keyword_arg = i
> make_kw("Z R X")
>
> # Now you can use them in indexing
> some_obj[5, Z:3]
> some_obj[7, Z:3, R:4]
>
> The parameters will arrive in the item tuple as slice objects, where
> the start is a signature object and the stop is its value.
>
> >>> some_obj[5, Z:3]
> getitem: (5, slice(<__main__.kw object at 0x016C5E10>, 3, None))
>
> Yes, it uses a colon rather than an equals sign, but on the flip side,
> it already works :)

This works great, IIRC you can pretty much pass *anything*:

dict[{}:]
dict[AType:lambda x: x]
dict[::]
dict[:]

...don't forget extended slice possibilities :)

I've dabbled with this in custom dict implementations and it usefully
excludes all normal dicts, which quickly reject slice objects.

-- 

C Anthony [mobile]
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20140701/0efba120/attachment.html>


More information about the Python-ideas mailing list