[Python-ideas] Accepting keyword arguments for __getitem__

Chris Angelico rosuav at gmail.com
Mon Jun 23 15:07:33 CEST 2014


On Mon, Jun 23, 2014 at 10:53 PM, Stefano Borini
<stefano.borini at ferrara.linux.it> wrote:
> On Mon, Jun 23, 2014 at 10:24:53PM +1000, Chris Angelico wrote:
>> The obvious way to accept that would be to support keyword arguments,
>> and then it begins looking very much like a call. Can you alter your
>> notation very slightly to become LDA(Z=5) instead?
>
> We certainly can, but I was wondering if such extension would be useful in other contexts.
> Also, with the function solution, you would lose the order of the entries. You can't distinguish
> foo(z=3, r=4) from foo(r=4, z=3)

Then you're asking for something where the syntax->semantics
translation is very different from the rest of Python. I suspect that
won't fly.

As an alternative, you may want to look into a preprocessor - some
sort of source code or concrete syntax tree transformation (you can't
use an AST transform unless you start with valid, compilable Python).
Translate this:

LDA[z=3, r=4]

into this:

LDA(("z",3),("r",4))

and then parse it off like this:

class A:
    def __call__(self, *args):
        for name, value in args:
            blah blah blah

I rather doubt your proposal would see much support in the rest of the
Python world, so a solution that's specific to your codebase would be
the way to go.

ChrisA


More information about the Python-ideas mailing list