[Python-ideas] Allowing def to assign to anything
MRAB
python at mrabarnett.plus.com
Tue Oct 27 00:35:34 EDT 2015
On 2015-10-26 07:27, Ian Kelly wrote:
>> On Sun, Oct 25, 2015 at 11:02 PM, Alexander Walters
>> <tritium-list at sdamon.com> wrote:
>>>
>>> In my code, I write a lot of dispatch dictionaries (for lack of a switch
>>> statement, but I will not hold my breath for that). In trying to make
>>> writing these dictionaries less annoying, I tend to use many lambdas. I can
>>> let you guess at what problems that has resulted in. Of course, the
>>> preferred way to write such dictionaries is by using a regular function, and
>>> adding that function to a dictionary. This isn't exactly a problem - it
>>> works, and works well, but it is annoying to write, and leaves artifacts of
>>> those functions in module scope. I propose a little bit of sugar to make
>>> this a little less annoying.
>>>
>>> If `def` is allowed to assign to anything (anything that is legal at the
>>> left hand side of an = in that scope), annoying artifacts go away. The
>>> syntax I propose should be backwards compatible.
>>>
>>> ```
>>> dispatch = {}
>>>
>>> def dispatch['foo'](bar):
>>> return bar * bar
>>> ```
>
> What about:
>
> def foo(bar)[baz](x):
> return x
>
> This seems like it would complicate parsing as the parser can't be
> sure whether (bar) is a parameter list or an argument list until it
> reaches the following [baz].
>
Would they be simpler to parse if they were:
def (bar) as dispatch['foo']:
return bar * bar
and:
def (x) as foo(bar)[baz]:
return x
?
In these instances, if there's no name then it should have the "as ..."
part; if there _is_ a name, then it shouldn't have the "as ..." part.
It's possible that:
def foo(bar):
return x
could just be a shorter way of writing:
def (bar) as foo:
return x
More information about the Python-ideas
mailing list