[Python-ideas] Yet Another Switch-Case Syntax Proposal

Ron Adam ron3200 at gmail.com
Sat Apr 26 16:58:27 CEST 2014



On 04/26/2014 09:54 AM, Chris Angelico wrote:
> On Sat, Apr 26, 2014 at 11:43 PM, Philipp A.<flying-sheep at web.de>  wrote:
>> >sure it works if `eggs` has a `__iadd__` method. why shouldn’t it use the
>> >outer local?
> 1) Operator precedence gets in the way. (Easily fixed.)
>>>> >>>lambda: eggs += lay_eggs()
> SyntaxError: can't assign to lambda
>
> 2) Assignment is a statement, so you can't do it in a lambda.
>>>> >>>lambda: (eggs += lay_eggs())
> SyntaxError: invalid syntax
>
> 3) Assignment makes it local, so you'll get UnboundLocalError if you
> don't declare it nonlocal.
>>>> >>>def f():
>      eggs += lay_eggs()
>>>> >>>f()
> Traceback (most recent call last):
>    File "<pyshell#5>", line 1, in <module>
>      f()
>    File "<pyshell#4>", line 2, in f
>      eggs += lay_eggs()
> UnboundLocalError: local variable 'eggs' referenced before assignment
>
> Hence my previous statement that you need to write the function out of
> line, which breaks the switch-ness of the block, and you definitely
> need to declare eggs nonlocal. Now, if eggs is a list, you can extend
> it with a method (which can be called in an expression), but if your
> switch block can only do expressions, it's pretty limited.

Another difference is a typical switch hash map is usually built at compile 
time in other languages.  In python, the example's dict would be built 
every time it executes.  That can be an advantage at times, but it can also 
make it slower than an if-elif's   Moving the dict (and function 
definitions) to a place where it's only initialised once, may mean the 
names it access may not be reachable, so in most cases any values it 
depends on need to be passed as well.

Ron



More information about the Python-ideas mailing list