interesting. it’s still assignment, even if nothing gets assigned (and only __iadd__ gets called behind the scenes).

2014-04-26 15:54 GMT+02:00 Chris Angelico <>:
On Sat, Apr 26, 2014 at 11:43 PM, Philipp A. <> 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>
  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.

Python-ideas mailing list
Code of Conduct: