[Python-ideas] Yet Another Switch-Case Syntax Proposal
Chris Angelico
rosuav at gmail.com
Sat Apr 26 15:54:19 CEST 2014
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.
ChrisA
More information about the Python-ideas
mailing list